Since Django 1.5 raw post data is accessible via request.body.
在我的应用程序中,我有时通过表单发送数据,有时通过原始数据(例如 json)发送数据。
有没有办法编写这样一个不会失败的函数?
def get_post_var(request, name):
result = request.POST.get(name)
if result:
return result
post_body = dict(urlparse.parse_qsl(request.body))
result = post_body.get(name)
if result:
return result
return None
最佳答案
错误 You cannot access body after reading from request's data stream
如果(1)该请求方法是 POST,(2)该请求的 POST 字典在中间件中访问,则将在请求时触发,在 process_request
中或 process_view
(3) 在 View 函数中,request.body
被访问。即使错误的真正原因是 (2),也会在 (3) 上引发错误。
为了解决该错误,您需要检查您的中间件访问 request.POST
的位置。并修改它使其不访问 request.POST
了。
Django 文档说 middleware should not access request.POST
,这是忽略该建议的后果之一。
另请查看 this Django ticket on the issue ,其中包括注释:
[M]iddleware that hits request.POST should (usually) be considered a bug. It means that the view will be unable to set any custom upload handlers, perform custom parsing of the request body, or enforce permission checks prior to file uploads being accepted.
关于django - 异常(exception):从请求的数据流中读取后无法访问正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581110/