python - 当 pytest 与 REST 框架交互时,PATCH 和 PUT 无法按预期工作

标签 python django-rest-framework put pytest-django

我正在使用 django REST 框架构建 API。

为了测试此 API,我正在使用 pytest 和测试客户端,如下所示:

def test_doesnt_find(self, client):
    resp = client.post(self.url, data={'name': '123'})
    assert resp.status_code == 404

def test_doesnt_find(self, client):
    resp = client.get(self.url, data={'name': '123'})
    assert resp.status_code == 404

在使用 REST 框架的一般 GET、POST 和 DELETE 类(如 DestroyAPIViewRetrieveUpdateAPIView 或只是 APIView 使用 get和发布功能)

我在使用 PATCH 和 PUT View 时遇到问题。如RetrieveUpdateAPIView。在这里我突然不得不使用:

resp = client.patch(self.url, data="name=123", content_type='application/x-www-form-urlencoded')

resp = client.patch(self.url, data=json.dumps({'name': '123'}), content_type='application/json')

如果我只是像往常一样尝试使用测试客户端,我会收到错误消息:

rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.

当我在 client.patch() 调用中指定“application/json”时:

rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`

任何人都可以向我解释这种行为吗?它特别难以捕捉,因为使用 -X PATCH -d"name=123" 时,curl 也能正常工作。

最佳答案

rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`

这通常表示您在 json 中的字符串中发送了一个字符串。 例如:

resp = client.patch(self.url, data=json.dumps("name=123"), content_type='application/json')

会导致此类问题。

rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.

这意味着请求已作为“application/octet-stream”发送,这是 Django 的测试默认值。

为了减轻处理所有这些的痛苦,Django REST 框架自己提供了一个客户端:http://www.django-rest-framework.org/api-guide/testing/#apiclient

请注意,语法与 Django 的略有不同,您不必处理 json 编码。

关于python - 当 pytest 与 REST 框架交互时,PATCH 和 PUT 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39906956/

相关文章:

python - 使用 DRF 序列化程序验证包含动态键的嵌套字典

python - 分页不适用于我的 Django Rest 框架项目,并且我正在使用通用 View

web-services - 在 RESTful 服务中部分更新复杂类型

php - retrofit2 发送 PUT 请求方法对于 PHP 是错误的

javascript - HTTP PUT 方法返回未找到错误

python - 使用 BeautifulSoup 抓取 Pantip 论坛

python - 如何在 python 中使用 FFmpeg 和 subprocess 模块将 .mp4 视频文件转换为 .yuv (YUV420),反之亦然?

python - 如何使用 Boto3 在 Dynamodb 上将项目添加到 string_set

python - 无效请求错误 : Could not find a FROM clause to join from

python - Django rest framework permission_classes of ViewSet 方法