码迷,mamicode.com
首页 > 其他好文 > 详细

Django,COOKIES,SESSION完成用户登入

时间:2018-12-26 13:30:18      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:func   utf-8   head   ssi   info   操作   imp   body   rect   

1.urls.py

"""Django_cookie_session URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path(‘‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path(‘‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path(‘blog/‘, include(‘blog.urls‘))
"""
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),
]

2.views.py

from django.shortcuts import render, redirect

# Create your views here.


def login(request):
    print(‘COOKIES:-->‘, request.COOKIES)
    print(‘SESSION:-->‘, request.session)

    if request.method == ‘POST‘:
        print(‘POST!!!‘)
        name = request.POST.get(‘user‘)
        pwd = request.POST.get(‘pwd‘)

        print(name)
        print(pwd)

        if name == ‘ck‘ and pwd == ‘123‘:
            # ret = redirect(‘/index/‘)
            # ret.set_cookie(‘user‘, name)
            # return ret
            request.session[‘is_login‘] = True
            request.session[‘user‘] = name
            return redirect(‘/index/‘)

    return render(request, ‘login.html‘)


def index(request):

    # if request.COOKIES.get(‘username‘, None):
    #     name = request.COOKIES.get(‘username‘, None)
    #     return render(request, ‘index.html‘, locals())

    if request.session[‘is_login‘] == True:
        name = request.session.get(‘user‘, None)
        return render(request, ‘index.html‘, locals())
    else:
        return redirect(‘/login/‘)

3.index.html

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

4.login.html

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

 cookies和session是浏览器在访问服务器端口时与连接请求一起发送的内容。

 目的是实现用户的登入操作,通过判断用户有没有对应的cookie或是session判断用户登入与否并从中获取用户的个人信息。

 cookies与session的区别是session的用户信息是存在服务器端,浏览器提供自己的键,对应的是服务端的键值就是用户的信息。这样保证用户的信息安全。

 

Django,COOKIES,SESSION完成用户登入

标签:func   utf-8   head   ssi   info   操作   imp   body   rect   

原文地址:https://www.cnblogs.com/CK85/p/10178562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!