根据要求在Django中间件中添加自定义标头 [英] Add a custom header on request in a Django middleware
问题描述
我想在django中实现一个中间件,该中间件将在 get_response(request)函数之前在请求的现有标头上附加一个标头.
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'
我收到一个错误:'HttpHeaders'对象不支持项目分配
同样在Django的请求(WSGIRequest)中,没有像python的请求模块这样的add_headers函数.
有关如何实现此目标的任何想法?
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?
推荐答案
创建如下所示的简单中间件,并将路径放在 MIDDLEWARE
设置.
Create a simple middleware as below, and put the path in the MIDDLEWARE
settings.
from django.utils.deprecation import MiddlewareMixin
class CustomHeaderMiddleware(MiddlewareMixin):
def process_request(self, request):
request.META['HTTP_CUSTOM_HEADER'] = "CUSTOM VALUE"
这篇关于根据要求在Django中间件中添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!