在Django中获取请求正文作为字符串 [英] Get request body as string in Django
问题描述
我正在向Django服务器发送带有JSON主体的POST请求(相当标准)。在服务器上,我需要使用 json.loads()
解码。
I'm sending a POST request with JSON body to a Django server (fairly standard). On the server I need to decode this using json.loads()
.
问题是如何获得请求的正文以字符串格式?
The problem is how do I get the body of the request in a string format?
我现在有以下代码:
body_data = {}
if request.META.get('CONTENT_TYPE', '').lower() == 'application/json' and len(request.body) > 0:
try:
body_data = json.loads(request.body)
except Exception as e:
return HttpResponseBadRequest(json.dumps({'error': 'Invalid request: {0}'.format(str(e))}), content_type="application/json")
但是,这给了一个错误 JSON对象必须是str,而不是'bytes'
。
However, this gives an error the JSON object must be str, not 'bytes'
.
请求身份为字符串,应用正确的编码?
How do I retrieve the body of the request as a string, with the correct encoding applied?
推荐答案
请求正文 request.body
,是一个字节字符串。在Python 3中, json.loads()
只会接受一个unicode字符串,所以你必须解码 request.body
将它传递给 json.loads()
。
The request body, request.body
, is a byte string. In Python 3, json.loads()
will only accept a unicode string, so you must decode request.body
before passing it to json.loads()
.
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
在Python 2中, json.loads
将接受unicode字符串或字节sting,因此解码步骤是不必要的。
In Python 2, json.loads
will accept a unicode string or a byte sting, so the decode step is not necessary.
当解码字符串时,我想你可以放心假设'utf-8' - 我找不到一个确定的源代码,但是从 jQuery文档:
When decoding the string, I think you're safe to assume 'utf-8' - I can't find a definitive source for this, but see the quote below from the jQuery docs:
注意:W3C XMLHttpRequest规范要求字符集始终为UTF-8;指定另一个字符集不会强制浏览器更改编码。
Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
这篇关于在Django中获取请求正文作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!