Django,COOKIES,SESSION完成使用者登入
阿新 • • 發佈:2018-12-26
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的使用者資訊是存在伺服器端,瀏覽器提供自己的鍵,對應的是服務端的鍵值就是使用者的資訊。這樣保證使用者的資訊保安。