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
Trying to parse `request.body` from POST in Django
提问by Zach
For some reason I cannot figure out why Django isn't handling my request.body
content correctly.
出于某种原因,我无法弄清楚为什么 Django 没有request.body
正确处理我的内容。
It is being sent in JSON
format, and looking at the Network
tab 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.body
I 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 json
after 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 编码的)。