Django框架學習筆記(21.Session例項)
阿新 • • 發佈:2018-12-29
基於Cookie做使用者驗證時:不適合把敏感資訊(如密碼)放在Cookie中,因為可以Cookie是可以看見的。
Cookie優勢:減輕了服務端的壓力
接下來介紹Session:
Cookie是儲存在使用者瀏覽器端的鍵值對
Session是儲存在伺服器端的鍵值對,不過它還得依賴於Cookie
Session原理是生成隨機字串,對應一個放入資料的字典,Cookie傳遞這個隨機字串進行驗證。
在Django中,簡化了這個複雜的過程。
注意在用session使用之前要:makemigrations,migrate,因為Django的session預設儲存在資料庫中
例項:建立配置完成後:
urls.py:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', views.login), url(r'^index/$', views.index), url(r'^logout/$', views.logout), ]
view.py:
from django.shortcuts import render, redirect, HttpResponse # Create your views here. def login(request): if request.method == "GET": return render(request, 'login.html') elif request.method == "POST": user = request.POST.get('user') pwd = request.POST.get('pwd') if user == "root" and pwd == "123": # 生成隨機字串 # 寫入使用者瀏覽器Cookie # 儲存到Session中 # 在隨機字串對應的字典中設定相關內容request.session['username'] = user request.session['is_login'] = True if request.POST.get('rmb', None) == '1': request.session.set_expiry(60*60*24) #設定超時時間,預設的是兩週 return redirect('/index/') else: return render(request, 'login.html') def index(request): if request.session.get('is_login', None): return render(request, 'index.html', {'username': request.session['username']}) else: return HttpResponse('錯誤') def logout(request): request.session.clear() return redirect('/login/')
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="user"/> <input type="password" name="pwd"/> <input type="checkbox" name="rmb" value="1"/>一天內免登入 <input type="submit" value="登入"/> </form> </body> </html>
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>歡迎{{ username }}登入:{{ request.session.username }}</h1> <a href="/logout/">登出</a> </body> </html>
效果:
在settings.py裡面還有很多有關session的配置:
SESSION_COOKIE_AGE = 1209600 #session的cookie失效日期,預設兩週 SESSION_EXPIRE_AT_BROWSER_CLOSE = False #是否關閉瀏覽器使SESSION過期 SESSION_SAVE_EVERY_REQUEST = True #是否每次請求都儲存session,預設False,這裡一般要改成True
設定session存放在哪裡:
#SESSION_ENGINE = 'django.contrib.sessions.backends.db' #設定儲存在資料庫 SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '172.19.26.240:11211', '172.19.26.242.11211', ] } } #設定在快取