【问题标题】:You cannot access body after reading from request's data stream after starting py.test启动 py.test 后从请求的数据流中读取后无法访问正文
【发布时间】:2014-02-18 06:41:37
【问题描述】:

下午好。

我正在使用 pytest 测试基于 django-rest-framework 的 api。我有以下创建新对象的方法(方法取自here):

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
@api_view(('POST',))
@permission_classes((IsAuthenticated, ))
def create_transaction(request):
    """
    The method takes the data in JSON-format.
    If the data is correct Transaction object will created, otherwise it returns an error also in JSON-format.
    """

    stream = StringIO('[' + request.raw_post_data + ']')
    data = JSONParser().parse(stream)
    serializer = NewTransactionSerializer(data=data, many=True)
    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data, status=201)
    else:
        return JSONResponse(serializer.errors, status=400)

我在下次测试时写信给它:

@pytest.mark.django_db
def test_create_method(client):
    correct_data = '''{ "var1": "111",
                        "var2": "222",
                        "var3": 2 }'''
    client.login(username='test2@github.com', password='test')
    data = json.loads(correct_data)
    response  = client.post('/rest2/create_transaction/', data, format='json')
    content = json.loads(response.content)
    assert content[0]['var1'] == '111'
    assert content[0]['var2'] == '222'
    assert content[0]['var3'] == 2
    assert response['Content-Type'] == 'application/json'
    assert response.status_code == 201

启动 pytest 时显示以下内容:Exception: You cannot access body after reading from request's data stream。当我将数据发布到 url 时它坏了。 当我在 shell 中运行相同的代码时,代码运行没有问题。我是测试新手,可能会遗漏一些东西,请帮忙。

【问题讨论】:

  • 您能否在加载response.content 之前尝试做出Content-Type 和status_code 断言?另外,请提供完整的追溯。
  • 它没有改变任何东西,因为错误出现在之前。回溯 - pastebin.com/ZrHTeFme
  • 我也遇到了这个问题。会尝试调查一下。

标签: python django http-post django-rest-framework pytest


【解决方案1】:

如果您使用的是 django-rest-framework,那么您可以只使用 request.data 而不是自己尝试从请求中解析 json

http://www.django-rest-framework.org/api-guide/requests/

 stream = StringIO('[' + request.raw_post_data + ']')
 data = JSONParser().parse(stream)

这可以替换为

data = request.data

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 2021-03-13
    • 2020-11-12
    • 1970-01-01
    • 2019-11-21
    • 2023-03-14
    • 1970-01-01
    • 2020-01-29
    • 2017-06-19
    相关资源
    最近更新 更多