且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-03 18:20:14

在 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).