Django之session验证的三种姿势
生活随笔
收集整理的這篇文章主要介紹了
Django之session验证的三种姿势
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.什么是session
session是保存在服務端的鍵值對,Django默認支持Session,并且默認是將Session數據存儲在數據庫中,即:django_session 表中。
二.FVB中使用裝飾器進行session驗證
認證裝飾器:
# 登陸驗證 def auth(func):'''判斷是否登錄裝飾器'''def inner(request, *args, **kwargs):ck = request.session.get("username")'''如果沒有登陸返回到login.html'''if not ck:return redirect("/login.html")return func(request, *args, **kwargs)return inner在需要認證的函數執行前加上裝飾器認證即可,實際中應用如下:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def login(request):if request.method == "GET":return render(request, "login.html")else:username = request.POST.get("user")pwd = request.POST.get("pwd")pwd = md5(pwd)dic = {"flag":False}obj = User.objects.filter(username=username, pwd=pwd).first()if obj:request.session["username"] = usernamereturn redirect("/index.html")else:print(dic)return HttpResponse(json.dumps(dic))@auth def index(request):user = request.session.get("username")business = Business.objects.all().values("name")host_list = Host.objects.all().values("id","host","port","business__name")username = User.objects.all().values("username")return render(request, 'index.html', {'host_list':host_list,"business":business,"user":user,"username":username})@auth def addhost(request):business = Business.objects.all().values("name")if request.method == "POST":user = request.session.get("username")host = request.POST.get("host")port = request.POST.get("port")select_business = request.POST.get("business")business_id = Business.objects.filter(name=select_business).values("id")[0]host = Host.objects.create(host=host,port=port,business_id=business_id["id"])# host.business.add(*business)return render(request, "index.html")return render(request, "index.html", {"business":business})@auth def up_business(request):if request.method == "POST":user = request.session.get("username")host= request.POST.get("host")port= request.POST.get("port")business_name = request.POST.get("business")username = request.POST.get("username")print(host,port,business_name,username)return render(request,"保存成功")三.CBV中使用類繼承的方式進行session認證
- cbv是 class based view(基于類)
- cbv基于dispatch進行反射,get獲取,post提交
- 應用場景:登錄認證(繼承dispatch,在dispatch里做session驗證)
- CBV第一種方式繼承
1.單繼承
掃盲:(繼承的時候,一定要清楚self是哪個類實例化出來的對象,下例,self為B實例化的對象,任何屬性優先從自己里面找,找不到在去父類里找)
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' class A(object):def aaa(self):print('from A')def bbb(self):self.aaa()class B(A):def aaa(self):print('from B')c = B() c.aaa()應用:
from django.views import View class BaseView(View):def dispatch(self, request, *args, **kwargs): # 繼承父類的dispatch,因為父類里有返回值,所以也要有returnif request.session.get('username'):response = super(BaseView, self).dispatch(request, *args, **kwargs)return responseelse:return redirect('/login.html')class IndexView(BaseView):def get(self, request, *args, **kwargs):return HttpResponse(request.session['username'])2.多繼承(繼承順序從左到右)
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' class BaseView(object):def dispatch(self, request, *args, **kwargs):if request.session.get('username'):response = super(BaseView,self).dispatch(request, *args, **kwargs)return responseelse:return redirect('/login.html')class IndexView(BaseView,View):#先去找BaseView,BaseView中未定義在去找Viewdef get(self,request,*args,**kwargs):return HttpResponse(request.session['username'])CBV第二種方式裝飾器
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' from django.utils.decorators import method_decoratordef auth(func): #定義裝飾器def inner(request,*args,**kwargs):if request.session.get('username'):obj = func(request,*args,**kwargs)return objelse:return redirect('/login.html')return inner@method_decorator(auth,name='get') #放在類頂部就需要method_decorator這個裝飾器 class IndexView(View):@method_decorator(auth) #放在dispatch上就相當于全局都需要經過認證def dispatch(self, request, *args, **kwargs):if request.session.get('username'):response = super(IndexView,self).dispatch(request, *args, **kwargs)return responseelse:return redirect('/login.html')@method_decorator(auth)def get(self,request,*args,**kwargs):return HttpResponse(request.session['username'])@method_decorator(csrf_exempt) # 無效 csrf 放到post函數上的裝飾器,是無效的,需要放到dispath上或者類上def post(self,request,*args,**kwargs):return HttpResponse(request.session['username'])四.中間件middleware
如下是django的生命周期
如下為中間件的執行順序
中間件執行時機:請求到來,請求返回時
- 中間件是一個類:
- 應用:
- 請求日志
- 用戶登錄認證
Django根目錄新建md文件夾,新建Middleware.py文件
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' from django.utils.deprecation import MiddlewareMixinclass M1(MiddlewareMixin):'''先執行request,然后到url路由,url之后返回到最上方,在執行view,如果出現錯誤就直接到response上,執行完,到真正到視圖,如果有問題就執行exception,從下至上查找,如果找到exception就直接執行exception的return在走response返回用戶每個中間件中,4個方法不需要都寫.'''def process_request(self,request):if request.path_info == "/login.html":return Noneuser_info = request.session.get("username")if not user_info:return redirect("/login.html")注:新的django版本可能不存在MiddlewareMixin,需要手動寫一下這個類進行繼承
class MiddlewareMixin(object):def __init__(self, get_response=None):self.get_response = get_responsesuper(MiddlewareMixin, self).__init__()def __call__(self, request):response = Noneif hasattr(self, 'process_request'):response = self.process_request(request)if not response:response = self.get_response(request)if hasattr(self, 'process_response'):response = self.process_response(request, response)return responseclass M1(MiddlewareMixin):def process_request(self,request):if request.path_info == "/login.html":return Noneuser_info = request.session.get("username")if not user_info:return redirect("/login.html")settings里配置:
MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','md.Middleware.M1', ]WSGI_APPLICATION = 'BBS.wsgi.application'SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默認)SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在瀏覽器上時的key,即:sessionid=隨機字符串(默認) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路徑(默認) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默認) SESSION_COOKIE_SECURE = False # 是否Https傳輸cookie(默認) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http傳輸(默認) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默認) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否關閉瀏覽器使得Session過期(默認) SESSION_SAVE_EVERY_REQUEST = True # 是否每次請求都保存Session,默認修改之后才保存(默認)總結
以上是生活随笔為你收集整理的Django之session验证的三种姿势的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django | 执行项目下指定的脚本
- 下一篇: django orm 常用查询筛选