十七、django中间件

PS:需要在setting中配置中间件的类路径

'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, '请登陆!')

 

 
posted @ 2019-11-16 19:08  颜颜blog  阅读(121)  评论(0编辑  收藏  举报