Django自定义中间件未添加自定义标头

时间:2019-12-13 10:36:00

标签: python django django-middleware

因此,我尝试向Django应用程序中的每个请求添加自定义标头,我遵循了this问题,设置如下:

middleware.py

from django.utils.deprecation import MiddlewareMixin


class ReverseProxyLocalMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.META['User-Id'] = 1

settings.py

...
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'myapp.middleware.ReverseProxyLocalMiddleware',
]

views.py

class UserViewSet(
    viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin
):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserSerializer

    def get_queryset(self):
        return models.User.objects.active(dt=timezone.now())

    def list(self, request):
        user_id = request.META['User-Id']
        ...

但是,任何时候我尝试在测试中访问新标头时都会得到:

    def list(self, request):
>       user_id = request.META['User-Id']
E       KeyError: 'User-Id'

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

结果证明,如果Django的标头不是HTTP_*_*格式,则它会删除标头,因此中间件必须如下所示:

from django.utils.deprecation import MiddlewareMixin


class ReverseProxyLocalMiddleware(MiddlewareMixin):
    def process_request(self, request, user_id=1):
        request.META['HTTP_USER_ID'] = user_id