django中session使用和用户认证装饰器

1、创建应该app01, 并在settings.py里面设置

 

2、在app01/ views.py视图里, 创建login 、 logout视图

from django.shortcuts import render, redirect, HttpResponse

# Create your views here.

def login_auth(func):
    def inner( request, *args, **kwargs ):
        if request.session.get("name"):
            return  func(request, *args , **kwargs)
        else:
            old_path = request.get_full_path()
            return redirect("/login/?next=%s" % old_path)
    return inner

def login(request):
    print( request.get_full_path())
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username == "egon"  and password == "123":
            request.session["name"] = "egon"
            request.session.set_expiry(0)
            old_path =  request.GET.get("next")
            if old_path:
                red = redirect(old_path)
            else:
                red = redirect("/index")
            return  red
    return render(request, "login.html")

@login_auth
def index(request):
    return HttpResponse("我是index页面,只有登录的才能访问")


@login_auth
def home(request):
    return HttpResponse("我是home页面,只有登录的才能访问")


def logout(request):
    request.session.clear()
    return render(request,"login.html")


def setSession(request):
    print(request.session)
    print(request.session.get("name"))
    request.session["name"] = "egon_2"
    return  HttpResponse("设置session")

3、创建 模板 templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="" method="POST">
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
    <p>用户名:<input type="text" name="username"> </p>
    <p>密 码:<input type="password" name="password"> </p>
    <p>用户名:<input type="submit" value="登录"> </p>
</form>

</body>
</html>

 

4、配置路由

from django.contrib import admin
from django.urls import path
from app01 import  views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("login/", views.login),
    path("index/", views.index),
    path("home/", views.home),
    path("logout/", views.logout),
    path("set_session/", views.setSession),
]

 

5、运行结果如下:

 

 

 

 访问后,设置session,是存放在数据库 django_session表中的

 

 

 

 

 

 

 

 

posted on 2019-11-14 20:00  芦苇草鱼  阅读(382)  评论(0编辑  收藏  举报