例外:从请求的数据流中读取后,您无法访问正文 [英] Exception: You cannot access body after reading from request's data stream
问题描述
由于 Django 1.5 原始帖子数据可通过 request.body 访问.
在我的应用程序中,我有时会通过表单获取数据,有时还会获取原始数据(例如 json).有没有办法写出这样一个不会失败的函数?
In my application I sometimes get data send via a form and sometimes raw data (json for example). Is there any way to write a function like this that does not fail?
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
推荐答案
如果 (1) 请求方法为POST,(2) 请求的 POST 字典在中间件中访问,在 process_request
或 process_view
和 (3) 在视图函数中,request.body代码> 被访问.即使错误的真正原因是 (2),也会在 (3) 上引发错误.
The error You cannot access body after reading from request's data stream
will be triggered on a request if (1) that request method is POST, (2) that request's POST dictionary is accessed in middleware, in either process_request
or process_view
and (3) within the view function, request.body
is accessed. It is on (3) that the error will be raised, even though the real cause of the bug is (2).
为了解决错误,您需要检查中间件访问 request.POST
的位置并对其进行修改,使其不访问 request.POST
没有了.
In order to resolve the error, you need to examine your middleware for where it accesses request.POST
and modify it such that it doesn't access request.POST
anymore.
Django 文档说 中间件不应该访问 request.POST
,这是忽略该建议的后果之一.
The Django docs say that middleware should not access request.POST
, and this is one consequence of ignoring that recommendation.
还可以查看this Django ticket on the issue,其中包括注释:
Also check out this Django ticket on the issue, which includes the note:
[M]命中 request.POST 的中间件应该(通常)被认为是漏洞.这意味着视图将无法设置任何自定义上传处理程序,执行请求正文的自定义解析,或强制执行在文件上传被接受之前进行权限检查.
[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.
这篇关于例外:从请求的数据流中读取后,您无法访问正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!