Add a custom header on request in a Django middleware

China☆狼群 提交于 2020-03-26 06:08:11

问题


I want to implement a middleware in django, that will append a header on the request's existing headers, before the get_response(request) function.

Though, when trying like this:

request.headers['CUSTOM_HEADER'] = 'CUSTOM_VALUE'

I get an error: 'HttpHeaders' object does not support item assignment
Also in django's request (WSGIRequest), there is no add_headers function like the python's request module.
Any ideas on how this can be accomplished?


回答1:


Create a simple middleware as below, and put the path in the MIDDLEWARE settings.

from django.utils.deprecation import MiddlewareMixin


class CustomHeadeerMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.META['HTTP_CUSTOM_HEADER'] = "CUSTOM VALUE"


来源:https://stackoverflow.com/questions/56632988/add-a-custom-header-on-request-in-a-django-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!