• Django 实现用户认证set_Cookie


    当用户通过认证时,set_Cookie(key, value)

    request.Cookie.get(key) 如果key不为空,就说明验证通过,否者重新跳转回login登录页面

    对于URL

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^tp1/', views.tp1),
        url(r'^user_list', views.user_list),
        url(r'^login', views.login),
        url(r'^Order/', views.Order.as_view()),
        url(r'^index/', views.index)
    ]

    对于views文件

    user = {'name':'dacengzi', 'password':123}
    def login(request):
        if request.method == 'GET':  #如果进来的方式是GET,直接跳转
            return render(request, 'login.html')
        elif request.method == 'POST': #如果是POST,说明用户已经上传
            username = request.POST.get('username')  #获取用户名
            password = int(request.POST.get('password')) #获取密码
            current_time = datetime.datetime.utcnow()  #当前时间
            current_time = current_time + datetime.timedelta(seconds=5)  #当前时间推迟5秒
    
            if username == user['name'] and password == user['password']: #如果用户名和密码匹配
                req = redirect('/index/')
    
                req.set_cookie('correct', username, expires=current_time) #设置Cookie标志位
                return  req
            else:
                return render(request, 'login.html')
    def auth(func):
        def inner(request, *args, **kwargs):
            answer = request.COOKIES.get('correct')  #接收验证所得的标志位
            if not answer:  #如果没有收到重新跳转回登录界面
                return render(request, 'login.html')
            else:  # 如果有就执行Order文件
                return func(request, *args, **kwargs)
        return inner
    from django.utils.decorators import method_decorator
    from django import  views
    @method_decorator(auth, name='dispatch')  #给dispatch加装饰器,程序一进来就进行验证
    class Order(views.View):
        def get(self, request):
            u = request.COOKIES.get('correct') #获取u,进行传递
            return render(request, 'index.html', {'u': u})
    
    def index(request):
        return render(request, 'index.html')

    对于login文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/login/" method="post">
        <input type="text" name="username">
        <input type="text" name="password">
        <input type="submit" value="提交">
        </form>
    </body>
    </html>
  • 相关阅读:
    代码质量检查那点事
    DataTable中如何去除重复的项【转】
    TAG的用法和用途[转]
    Sqlite: unable to open database file
    [转]DataGridView绑定泛型List的种种
    SQLite清空表并将自增列归零[转]
    .NET特性-Attribute
    基于边信道的硬件攻击小综述
    国内下载vscode速度慢解决
    centos与内核版本对应关系
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/9477716.html
Copyright © 2020-2023  润新知