Python 尝试从 Django 中的 POST 解析`request.body`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29780060/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:00:41  来源:igfitidea点击:

Trying to parse `request.body` from POST in Django

pythonjsondjangopython-3.xbackbone.js

提问by Zach

For some reason I cannot figure out why Django isn't handling my request.bodycontent correctly.

出于某种原因,我无法弄清楚为什么 Django 没有request.body正确处理我的内容。

It is being sent in JSONformat, and looking at the Networktab in Dev Tools shows this as the request payload:

它以JSON格式发送,查看Network开发工具中的选项卡将其显示为请求有效负载:

{creator: "creatorname", content: "postcontent", date: "04/21/2015"}

which is exactly how I want it to be sent to my API.

这正是我希望它被发送到我的 API 的方式。

In Django I have a view that accepts this request as a parameter and just for my testing purposes, should print request.body["content"]to the console.

在 Django 中,我有一个接受这个请求作为参数的视图,只是为了我的测试目的,应该打印request.body["content"]到控制台。

Of course, nothing is being printed out, but when I print request.bodyI get this:

当然,什么都没有打印出来,但是当我打印时,request.body我得到了这个:

b'{"creator":"creatorname","content":"postcontent","date":"04/21/2015"}'

so I know that I dohave a body being sent.

所以我知道我确实有一个身体被发送。

I've tried using json = json.loads(request.body)to no avail either. Printing jsonafter setting that variable also returns nothing.

我也试过用json = json.loads(request.body)也无济于事。json设置该变量后打印也不会返回任何内容。

采纳答案by Alasdair

In Python 3.0 to Python 3.5.x, json.loads()will only accept a unicode string, so you must decode request.body(which is a byte string) before passing it to json.loads().

在 Python 3.0 到 Python 3.5.x 中,json.loads()将只接受 unicode 字符串,因此您必须request.body在将其传递给json.loads().

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['content']

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, UTF-16 or UTF-32).

在 Python 3.6 中,json.loads()接受 bytes 或 bytearrays。因此您不需要解码request.body(假设它是用 UTF-8、UTF-16 或 UTF-32 编码的)。