Django rest框架解析器在执行所有语句之前返回

2024-10-04 03:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用{}和{}的最新版本,可在{}上的{}频道上找到-不过,这个问题在较旧的代码基({}版本{})上也可以重现

问题是当我尝试定义自定义解析器(按照here)时,下面显示了一个说明问题的示例:

import logging

import json
import jsonschema
from rest_framework.exceptions import ParseError
from rest_framework.parsers import JSONParser

log = logging.getLogger('logger')

class JSONCustomParser(JSONParser):

    def parse(self, stream, media_type=None, parser_context=None):
        data = super(JSONCustomParser, self). \
            parse(stream, media_type, parser_context)
        try:
            # these are executed normally
            a = 1
            b = 2

            # problematic bits: un-comment either of these and execution ends early.
            # data = json.load(stream.read())
            # data = json.load("{}")
            # data = JSONParser().parse(stream)
            # auth_name = str(parser_context['request'].auth.application)

            # sample commands not executed if they are *after* the above and either if them is
            # un-commented
            a = a + a
            b = a + 2
        except ValueError:
            log.error("Value error")
        except Exception as generic_exception:
            log.error(str(generic_exception))
        else:
            return data

还有一个非常简单的测试视图,您可以使用:

class TestView(APIView):
    """
    Simple test view to test the parser
    """
    parser_classes = (JSONCustomParser,)
    permission_classes = ()

    def post(self, request):
        content_length = request.META['CONTENT_LENGTH']

        return Response({'received': content_length})

我假设两个stream消费操作强制返回,尽管不太确定,因为流在super调用中被JSONParser消费。。。然而,我不确定为什么其他人会提出一个问题


Tags: importself版本logjsonparserdatastream