尝试从Django中的POST解析“request.body” [英] Trying to parse `request.body` from POST in Django
问题描述
由于某种原因,我无法确定Django为什么没有正确处理我的 request.body
内容。
For some reason I cannot figure out why Django isn't handling my request.body
content correctly.
它正在以 JSON
格式发送,并查看开发工具中的网络
选项卡将其显示为请求有效载荷:
It is being sent in JSON
format, and looking at the Network
tab in Dev Tools shows this as the request payload:
{creator: "creatorname", content: "postcontent", date: "04/21/2015"}
这正是我想要将其发送到我的API。
which is exactly how I want it to be sent to my API.
在Django我有一个视图接受这个请求作为一个参数,只是为了我的测试目的,应该打印 request.body [content]
控制台。
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.
当然没有打印出来,但是当我打印 request.body
我得到这个: p>
Of course, nothing is being printed out, but when I print request.body
I get this:
b'{"creator":"creatorname","content":"postcontent","date":"04/21/2015"}'
所以我知道我有一个正文发送。
so I know that I do have a body being sent.
我尝试使用 json = json.loads(request.body)
也没有用。
I've tried using json = json.loads(request.body)
to no avail either. Printing json
after setting that variable also returns nothing.
推荐答案
在Python中打印 json
3, json.loads()
只会接受一个unicode字符串,所以你必须解码 request.body
(这是一个字节字符串),然后传递给 json.loads()
。
In Python 3, 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()
.
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['content']
这篇关于尝试从Django中的POST解析“request.body”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!