Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1194
天命终不由人
天命终不由人 2021-01-30 10:37

I\'m trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser wit

相关标签:
7条回答
  • 2021-01-30 11:43

    I had the same issue and decided to change my design. Instead of using a Middleware I simply monkey-patch rest_framework.views.APIView.

    In my case I needed to patch check_permissions but you can patch whatever fits your problem. Have a look at the the source code.

    settings.py

    INSTALLED_APPS = [
        ..
        'myapp',
    ]
    

    myapp/patching.py

    import sys
    
    from rest_framework.views import APIView as OriginalAPIView
    
    
    class PatchedAPIView(OriginalAPIView):
        def check_permissions(self, request):
            print(f"We should do something with user {request.user}"
            return OriginalAPIView.check_permissions(self, request)
    
    
    # We replace the Django REST view with our patched one
    sys.modules['rest_framework'].views.APIView = PatchedAPIView
    

    myapp/__init__.py

    from .patching import *
    
    0 讨论(0)
提交回复
热议问题