我正在尝试通过要处理的 View 发布 json 数据并将其放入 View 中。 json 包含一个名为 x-pinpoint-token 的自定义 header 。但是,当我尝试通过 request.META.get 获取此数据时,它无法获取我需要的数据。
class Data(View):
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(IDFAData, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
token = request.META.get('X_PINPOINT_TOKEN')
if token is None:
return HttpResponse(
"Failed Authorization - 401",
status='401'
)
else:
token = token.split(':')
token_clean = token[1]
data_in = json.loads(request.body)
...
无论我传递什么, View token 似乎都是空的。
我用 python-requests
运行的测试:
import requests
token = '8756990800504b3f86a103bba1a03aab'
token = 'Token:'+token
data_in = {...}
import json
headers = {}
headers['content-type'] = 'application/json'
headers['X_PINPOINT_TOKEN'] = token
payload = json.dumps(data_in)
r = requests.post('http://0.0.0.0:5000/api/', headers=headers, data=payload)
但它只返回 401。
最佳答案
documentation for HttpRequest.META
说:
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.
所以试试 request.META.get('HTTP_X_PINPOINT_TOKEN')
。
(一个简单的调试方法是打印或记录 request.META.keys()
。)
关于python - 在 django 中使用自定义 http header 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962073/