Python 在 Django 中获取请求正文作为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29514077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get request body as string in Django
提问by zelanix
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()
.
我将带有 JSON 正文的 POST 请求发送到 Django 服务器(相当标准)。在服务器上,我需要使用json.loads()
.
The problem is how do I get the body of the request in a string format?
问题是如何以字符串格式获取请求的正文?
I have the following code currently:
我目前有以下代码:
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")
However, this gives an error the JSON object must be str, not 'bytes'
.
但是,这会产生错误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?
如何以字符串形式检索请求正文,并应用正确的编码?
采纳答案by Alasdair
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()
.
请求正文request.body
是一个字节字符串。在 Python 3 中,json.loads()
将只接受一个 unicode 字符串,因此您必须request.body
在将其传递给json.loads()
.
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
In Python 2, json.loads
will accept a unicode string or a byte sting, so the decode step is not necessary.
在 Python 2 中,json.loads
将接受 unicode 字符串或字节串,因此不需要解码步骤。
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:
在解码字符串时,我认为您可以安全地假设 'utf-8' - 我找不到明确的来源,但请参阅下面来自jQuery 文档的引用:
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.
注意:W3C XMLHttpRequest 规范规定字符集始终为 UTF-8;指定另一个字符集不会强制浏览器更改编码。
In Python 3.6, json.loads()
accepts bytes or bytearrays. Therefore you shouldn't need to decode request.body
(assuming it's encoded in UTF-8).
在 Python 3.6 中,json.loads()
接受 bytes 或 bytearrays。因此您不需要解码request.body
(假设它是用 UTF-8 编码的)。
回答by Aswin Murugesh
I believe that the other end from where you receive this request does not convert the data to JSON before sending the request. Either you have to convert the data to JSON before you send, or just try accessing request.body in your view.
我相信您收到此请求的另一端在发送请求之前不会将数据转换为 JSON。要么您必须在发送之前将数据转换为 JSON,要么尝试在您的视图中访问 request.body。
回答by Johan
If your goal is to end up with a dictionary of the data you have just sent to the server using JSON, save yourself the trouble of decoding the body yourself and use the request.POST
dictionary-like object django already provides out-of-the-box.
如果您的目标是使用 JSON 获得刚刚发送到服务器的数据字典,那么您可以省去自己解码正文的麻烦,并使用request.POST
django 已经提供的开箱即用的 类似字典的对象。
So suppose you POST this to the server:
因此,假设您将其 POST 到服务器:
{ 'foo': 'bar' }
Then the following method
那么下面的方法
def my_handler(request):
foo = request.POST['foo']
print(foo)
Would print bar
to the console
将打印bar
到控制台