如何访问tastypie自定义身份验证中的POST数据

era*_*ran 11 django tastypie

我正在尝试在tastypie中编写自定义身份验证.基本上,我想使用post参数进行身份验证,我根本不想使用django auth,所以我的代码看起来像:

class MyAuthentication(Authentication):
   def is_authenticated(self, request, **kwargs):
       if request.method == 'POST':
           token = request.POST['token']
           key = request.POST['key']
           return is_key_valid(token,key)
Run Code Online (Sandbox Code Playgroud)

这或多或少都是这个想法.问题是我不断收到以下错误:

"error_message": "You cannot access body after reading from request's data stream"
Run Code Online (Sandbox Code Playgroud)

我知道这与我正在访问POST的事实有关,但我无法确定是否有办法解决它.有任何想法吗?谢谢.

编辑:也许我忘了提到最重要的事情.我正在使用github中找到的技巧处理表单数据.我的资源来自多部分资源

class MultipartResource(object):
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')

        if format == 'application/x-www-form-urlencoded':
            return request.POST

        if format.startswith('multipart'):
            data = request.POST.copy()
            data.update(request.FILES)
            return data
        return super(MultipartResource, self).deserialize(request, data, format)
Run Code Online (Sandbox Code Playgroud)

K Z*_*K Z 12

问题是Content-Type您的请求中的标题未正确设置.[ 参考 ]

Tastypie只能识别xml,json,yamlbplist.因此,在发送POST请求时,您需要Content-Type在请求标头中设置其中任何一个(例如,application/json).

编辑:

看起来你正试图通过Tastypie发送带有文件的多部分表单.

关于Tastypie的文件上传支持,Issac Kelly为路线图1.0决赛提供了一些背景(尚未发布):

  1. 实现一个Base64FileField,它接受用于PUT/POST的base64编码文件(如问题#42中的那个),并提供GET请求的URL.这将是主要的tastypie repo的一部分.
  2. 我们希望鼓励其他实现作为独立项目实现.有几种方法可以做到这一点,而且大多数都有点挑剔,它们都有不同的缺点,我们希望有其他选择,并记录每个方法的优点和缺点.

这意味着至少现在,Tastypie并不正式支持多部分文件上传.然而,野外的叉子据说运作良好,是其中之一.我没有测试过它.


现在让我试着解释你遇到这个错误的原因.

在Tastypie resource.py,第452行:

def dispatch(self, request_type, request, **kwargs):
    """
    Handles the common operations (allowed HTTP method, authentication,
    throttling, method lookup) surrounding most CRUD interactions.
    """
    allowed_methods = getattr(self._meta, "%s_allowed_methods" % request_type, None)

    if 'HTTP_X_HTTP_METHOD_OVERRIDE' in request.META:
        request.method = request.META['HTTP_X_HTTP_METHOD_OVERRIDE']

    request_method = self.method_check(request, allowed=allowed_methods)
    method = getattr(self, "%s_%s" % (request_method, request_type), None)

    if method is None:
        raise ImmediateHttpResponse(response=http.HttpNotImplemented())

    self.is_authenticated(request)
    self.is_authorized(request)
    self.throttle_check(request)

    # All clear. Process the request.
    request = convert_post_to_put(request)
    response = method(request, **kwargs)

    # Add the throttled request.
    self.log_throttled_access(request)

    # If what comes back isn't a ``HttpResponse``, assume that the
    # request was accepted and that some action occurred. This also
    # prevents Django from freaking out.
    if not isinstance(response, HttpResponse):
        return http.HttpNoContent()

    return response
Run Code Online (Sandbox Code Playgroud)

convert_post_to_put(request)从这里打电话.以下是代码 convert_post_to_put:

# Based off of ``piston.utils.coerce_put_post``. Similarly BSD-licensed.
# And no, the irony is not lost on me.
def convert_post_to_VERB(request, verb):
    """
    Force Django to process the VERB.
    """
    if request.method == verb:
        if hasattr(request, '_post'):
            del(request._post)
            del(request._files)

        try:
            request.method = "POST"
            request._load_post_and_files()
            request.method = verb
        except AttributeError:
            request.META['REQUEST_METHOD'] = 'POST'
            request._load_post_and_files()
            request.META['REQUEST_METHOD'] = verb
        setattr(request, verb, request.POST)

    return request


def convert_post_to_put(request):
    return convert_post_to_VERB(request, verb='PUT')
Run Code Online (Sandbox Code Playgroud)

并且这个方法并不是真正用于处理multipart,因为它具有防止进一步访问的副作用,request.body因为 _load_post_and_files()method会将_read_startedflag 设置为True:

Django request.body_load_post_and_files():

@property
def body(self):
    if not hasattr(self, '_body'):
        if self._read_started:
            raise Exception("You cannot access body after reading from request's data stream")
        try:
            self._body = self.read()
        except IOError as e:
            six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])
        self._stream = BytesIO(self._body)
    return self._body

def read(self, *args, **kwargs):
    self._read_started = True
    return self._stream.read(*args, **kwargs)

def _load_post_and_files(self):
    # Populates self._post and self._files
    if self.method != 'POST':
        self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()
        return
    if self._read_started and not hasattr(self, '_body'):
        self._mark_post_parse_error()
        return

    if self.META.get('CONTENT_TYPE', '').startswith('multipart'):
        if hasattr(self, '_body'):
            # Use already read data
            data = BytesIO(self._body)
        else:
            data = self
        try:
            self._post, self._files = self.parse_file_upload(self.META, data)
        except:
            # An error occured while parsing POST data. Since when
            # formatting the error the request handler might access
            # self.POST, set self._post and self._file to prevent
            # attempts to parse POST data again.
            # Mark that an error occured. This allows self.__repr__ to
            # be explicit about it instead of simply representing an
            # empty POST
            self._mark_post_parse_error()
            raise
    else:
        self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
Run Code Online (Sandbox Code Playgroud)

所以,你可以(尽管可能不应该)通过调用convert_post_to_VERB()设置request._body来 修补Tastypie的 方法request.body,然后立即设置_read_started=False以便 _load_post_and_files()读取_body并且不会设置 _read_started=True:

def convert_post_to_VERB(request, verb):
    """
    Force Django to process the VERB.
    """
    if request.method == verb:
        if hasattr(request, '_post'):
            del(request._post)
            del(request._files)

        request.body  # now request._body is set
        request._read_started = False  # so it won't cause side effects

        try:
            request.method = "POST"
            request._load_post_and_files()
            request.method = verb
        except AttributeError:
            request.META['REQUEST_METHOD'] = 'POST'
            request._load_post_and_files()
            request.META['REQUEST_METHOD'] = verb
        setattr(request, verb, request.POST)

    return request
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚遇到了与OP相同的问题,并且根据您出色的解释,我尝试了以下非常简单的修复:在“MyAuthentication”类中,在返回之前添加行:“request._read_started = False”。这似乎有效。 (2认同)

Seb*_*ian 0

当您第二次访问 request.body(或 request.raw_post_data,如果您仍在 Django 1.3 上)时,或者我相信,如果您在访问 POST、GET、META 或 COOKIES 属性后访问它,则会发生此错误。

Tastypie 在处理 PUT 或 PATCH 请求时将访问 request.body (raw_post_data) 属性。

考虑到这一点,在不了解更多细节的情况下,我会:

  • 检查这是否仅发生在 POST/PUT 中。如果是这样,那么您将必须重写某些 tastypie 方法或放弃您的身份验证方法。
  • 在代码中查找访问 request.body (raw_post_data) 的位置
  • 查找可能尝试访问 body/raw_post_data 的第 3 方模块(可能是中间件)上的调用

希望这可以帮助!