django - 异常(exception):从请求的数据流中读取后无法访问正文

标签 django exception post request

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/

相关文章:

django - 找到默认的 ROUTING 键 - channel 2 中不再需要此键

python - 修改django装饰器函数,Permissionn_required

django - 错误 : No module named messages after installing python-django-debug-toolbar

c# - 当使用 "using"时,我们是否有任何情况可以包含 catch block ,我们可以在其中处理对象而不做任何其他事情

php - jquery POST 不在 https 中返回任何结果

c# - 如何将此 Perl 上传脚本转换为 C#?

django - 如何为谷歌表单等字段设计数据库?

exception - JUnit 中的多个预期异常

php - Laravel 5.5 $exception instanceof AuthenticationException 未按预期工作

ios - IONIC 3 - WKWebview CORS 问题