Django,COOKIES,SESSION完成用戶登入
阿新 • • 發佈:2018-12-26
服務 edi inf 在服務器 安全 get pre locals 瀏覽器
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完成用戶登入