Django中的自定义HTTP标头

Jas*_* Xu 27 django

我使用自定义的http标头进行名为"sign"的URL签名,如何在Django中获取这样的自定义HTTP标头值?

owe*_*ncm 59

继续使用:

request.META.get('HTTP_{your uppercased header name}')
Run Code Online (Sandbox Code Playgroud)

请注意,在Django中,您使用下划线而不是破折号在大写字母中编写标题名称,但在客户端的请求中,您必须使用破折号而不是下划线来编写它(出于安全原因,生产Web服务器将删除带有下划线的自定义标题).

因此,My-Custom-Header访问自定义标头request.META['HTTP_MY_CUSTOM_HEADER']


Jas*_* Xu 16

最后我发现只是通过了

request.META('HTTP_{your uppercased header name}')
Run Code Online (Sandbox Code Playgroud)


roc*_*ier 13

您可以将自己的自定义标头添加到响应中,如下所示:https: //docs.djangoproject.com/en/dev/ref/request-response/#setting-headers

>>> response = HttpResponse()
>>> response['Cache-Control'] = 'no-cache'
>>> del response['Cache-Control']
Run Code Online (Sandbox Code Playgroud)

或者使用装饰器将它们添加到视图中:http: //djangosnippets.org/snippets/275/


Roh*_*tri 6

我试图使用以下代码访问标题:

request.META.get('HTTP_{your uppercased header name}')
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用,然后我意识到自定义标题不应该包含underscore所以我改变了underscorewith dash和boom,一切都开始工作了.希望这能帮助像我这样的人.:-)


jla*_*tre 5

As of Django 2.2 you can use the HttpRequest.headers dictionary which provides case-insensitive dictionary of request headers, like such:

my_header = request.headers.get('x-my-custom-header')
Run Code Online (Sandbox Code Playgroud)

See django.http.HttpRequest.headers