尝试从 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
格式发送,查看 Dev Tools 中的 Network
选项卡将其显示为请求负载:
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
时,我得到了这个:
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)
也无济于事.设置该变量后打印 json
也不会返回任何内容.
I've tried using json = json.loads(request.body)
to no avail either. Printing json
after setting that variable also returns nothing.
推荐答案
在 Python 3.0 到 Python 3.5.x 中,json.loads()
只接受一个 unicode 字符串,所以你必须解码 request.body
(这是一个字节字符串),然后将其传递给 json.loads()
.
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()
.
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['content']
在 Python 3.6 中,json.loads()
接受字节或字节数组.因此,您不需要解码 request.body
(假设它以 UTF-8、UTF-16 或 UTF-32 编码).
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).
这篇关于尝试从 Django 中的 POST 解析`request.body`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!