如何从Django Headers获取数据?

时间:2018-05-29 12:19:12

标签: python django django-rest-framework django-views

我从Django Headers获取数据时遇到问题。

我的API使用CURL: -

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中,我需要获得xyzIdabcData

我尝试request.META['abcData'],但收到错误KeyError

如何在我的视图中获取这两个数据?

请帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:7)

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

  

除了CONTENT_LENGTH和CONTENT_TYPE之外,如上所述,请求中的任何HTTP头都将转换为META密钥,方法是将所有字符转换为大写,用下划线替换任何连字符,并在名称中添加HTTP_前缀。因此,例如,名为X-Bender的标头将映射到META密钥HTTP_X_BENDER。

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

request.META['HTTP_ABCDATA']

答案 1 :(得分:1)

如果我理解你的问题。

我相信你正在使用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模块,请稍微改进一下。

然后你可以提出要求。

head = {}
head['Cache-Control'] = 'no-cache'
head['Content-Type'] = 'application/json'
head['xyzId'] = '3223'
head['abcData'] = 'ABC-123'
x = request.post(url='https://xyx.com',headers = head)
print x.headers

如果您只想在Django View中访问HTTP标头,请按以上建议使用。

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

以上将为您提供所有标题。

希望这有帮助。