例外:从请求的数据流读取后,您无法访问正文 [英] Exception: You cannot access body after reading from request's data stream

查看:1004
本文介绍了例外:从请求的数据流读取后,您无法访问正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于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.

另外请查看此Django机票上的问题,其中包括:

Also check out this Django ticket on the issue, which includes the note:


[M]点击请求的中间件.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆