十7、django中間件

PS:須要在setting中配置中間件的類路徑redis

'my_test.middleware.SessionMiddleware',#校驗session的類
my_test 項目名稱同名目錄
middleware 自定義的中間件py文件
SessionMiddleware 實現中間件功能的類

from django.utils.deprecation import MiddlewareMixin import django_redis from .settings import no_login_list from user.utils import MyResponse import pickle class PutMethodMiddleware(MiddlewareMixin): # 全部的請求先走這裏,走完再去請求視圖
    def process_request(self,request): # print('中間件接收到請求了')
        # print('request.path_info',request.path_info)#請求的地址,是寫在urls.py裏面的連接
        # print('request.path',request.path)
        # print('request.get_full_path',request.get_full_path())
        # print('token',request.headers.get('token'))
        # print('request.FILES',request.FILES)
        # return JsonResponse({"ok":1})
        if request.method == 'PUT': # 若是是PUT請求,須要用parse_file_upload把data取出來
            put_data,files = request.parse_file_upload(request.META, request) # 由於這裏已經取過put的data了,因此在view裏面能夠直接用request.PUT取數據
            request.PUT = put_data request._files = files #request.FILES裏面取值的時候就是_files

    # 視圖請求完回來的時候走這裏
    def process_response(self,request,response): # print("中間件接收到響應")
        return response # 執行視圖前走這裏
    def process_view(self, request, view_func, view_args, view_kwargs): # print("中間件在執行%s視圖前" %view_func.__name__)
        pass

    # 視圖報錯走這裏
    def process_exception(self,request,exception): # print("中間件處理視圖異常...")
        pass

class SessionMiddleware(MiddlewareMixin): def process_request(self,request): for uri in no_login_list:#循環檢查是否須要登錄
            if uri in request.path_info:#若是在這個list裏面說明不用登錄,直接跳過
                break
            else: # 從header裏面獲取數據
                # HTTP_TOKEN 傳過來的token字段名爲token,前面必須加HTTP前綴並大寫
                # token = request.META.get('HTTP_TOKEN')
                token = request.GET.get('token')#爲了方便,先從url裏得到
                # print('token',token)
                redis = django_redis.get_redis_connection() if token: user_obj_bytes = redis.get(token) if user_obj_bytes: user = pickle.loads(user_obj_bytes)#從redis裏面取到用戶名
                        request.user = user #加到request裏面
                        request.token = token #把token加到request裏面
                    else: return MyResponse(-1,'請登錄!') else: return MyResponse(-1, '請登錄!')
相關文章
相關標籤/搜索