手写django的session

视图函数

# 视图函数中,简单使用session
request.SESSION.login = True
request.SESSION.get(key)
等等

中间件

# 中间件中实现session的底层原理
# 请求来的时候:process_request()

	1. 从request对象中获取COOKIE
    2. 查询SESSION数据库表,获取SESSION字典
    3. 将SESSION字典对象赋值给request对象

# 响应走的时候:process_response()
	1. 判断SESSION对象是否操作过:修改或删除等
    2. 生成一个随机字符串
    3. 更新SESSION数据库表
    4. 设置cookie,将随机字符串交由浏览器保存。

代码实现

# 视图
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        name = request.POST.get('username')
        pawd = request.POST.get('password')
        user_obj = auth.authenticate(username=name, password=pawd)
        if user_obj:
            request.SESSION.login = True
            # request.SESSION['login'] = True
        return HttpResponse('OK')
    
    
    
# 中间件
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
import json
from app01 import models, tools


class SessionDict(dict):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__['modify'] = False
        self.__dict__['delete'] = False

    def __setattr__(self, key, value):
        self.__dict__[key] = value
        self.__dict__['modify'] =True

    def __getattr__(self, item):
        return self.__dict__.get(item)

    def __setitem__(self, key, value):
        self.__dict__[key] = value
        self.__dict__['modify'] =True

    def flush(self):
        self.__dict__['delete'] = True

    def clear_expired(self):
        pass

    @property
    def session_key(self):
        return self.__dict__.get('_session_key', None)


class SessionplusMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path in ['/login/', '/register/']:
            request.SESSION =  SessionDict()
            return None
        random_str = request.COOKIES.get('session_id')
        session_obj = models.SessionDB.objects.filter(session_key=random_str).first()
        if not session_obj:
            request.SESSION = SessionDict()
            return redirect('login')
        request.SESSION = SessionDict(json.loads(session_obj.session_data))

    def process_response(self, request, response):
        if request.SESSION.modify:
            random_str = tools.md5(request.META.get('REMOTE_ADDR').encode('utf-8'))
            request.SESSION.__dict__['_session_key'] = random_str
            models.SessionDB.objects.create(session_key=random_str, session_data=json.dumps(request.SESSION.__dict__))
            response.set_cookie('session_id', random_str)
        if request.SESSION.delete:
            random_str = tools.md5(request.META.get('REMOTE_ADDR').encode('utf-8'))
            models.SessionDB.objects.filter(session_key=random_str).delete()
            response.delete_cookie('session_id')

        return response
posted @ 2020-07-03 23:11  the3times  阅读(131)  评论(0编辑  收藏  举报