python - 在 django 中使用自定义 http header 时遇到问题

标签 python json django

我正在尝试通过要处理的 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/

相关文章:

python - 我很难理解 scipy.optimize 的语法

python - TensorFlow 中矩阵和向量的高效逐元素乘法

python - 欺诈检测分类ML的经纬度转换

python - django 2 mysql 数据库后端不接受 0 作为 AutoField 错误的值

Django 通过消息引发 404

json - 如何获取主键相关字段嵌套序列化程序 django rest 框架的所有值

python - 自定义对象权限在 django rest 框架中不起作用

json - 如何通过结构重新格式化 JSON?

android - 解析复杂json数据时出现 flutter 问题

javascript - Webpack 如何使用 $translatePartialLoader 缓存 bust angular-translate?