如何从Django头文件中获取数据?

2024-10-01 17:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我面临着从Django头文件获取数据的问题。在

使用我的API卷曲:-在

curl -X POST \
  https://xyx.com \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'xyzId: 3223' \
  -H 'abcData: ABC-123' \
  -d '{
  "name": "xyz",
  "dob": "xyz",
  "user_info": "xyz",
}'

在我的API中,我需要得到xyzId和{}

我尝试了request.META['abcData'],但得到了错误KeyError。在

如何在视图中同时获取这两个数据?在

请帮我解决这个问题。在

提前谢谢。在


Tags: djangonohttpscomapicache头文件curl
2条回答

如果我理解你的问题。在

我相信你在消耗API。在

from urllib import request
with request.urlopen(url, data) as f:
    print(f.getcode())  # http response code
    print(f.info())     # all header info

    resp_body = f.read().decode('utf-8') # response body

以防使用requests模块。在

然后你可以提出请求。在

^{2}$

如果您只想在Django视图中访问HTTP头,那么就按照上面的建议使用。在

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

上面会给你所有的标题。在

希望这有帮助。在

根据文件说https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.META

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

所以你应该可以像这样访问你的头

request.META['HTTP_ABCDATA']

相关问题 更多 >

    热门问题