# middleware.py
from django.contrib.sessions.backends.db import SessionStore
from rest_framework.authtoken.models import Token

class TokenSessionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 在请求处理前绑定 Session
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            if auth_header.startswith('Token '):
                token_key = auth_header.split(' ')[1]
                try:
                    user = Token.objects.get(key=token_key).user
                    if user.session_key:
                        # 创建 Session 实例并加载数据
                        session = SessionStore(session_key=user.session_key)
                        session.load()
                        request.session = session
                except (Token.DoesNotExist, AttributeError):
                    pass

        # 继续处理请求（包括视图函数）
        response = self.get_response(request)
        
        # 响应阶段可选的保存逻辑
        if hasattr(request, 'session') and request.session.modified:
            request.session.save()
        
        return response