django-rest-framework http 在 django 1.5 上以 415 失败

标签 django django-rest-framework

我正在为 REST API 使用 django-rest-framework(最新),并使用内置测试客户端在 django 中实现了一些测试用例。

以下 django 测试用例在 django 版本 < 1.5 下运行良好

self.client.put('/core/accounts/%s/'% self.account.id,
        data = prepare_dict(self.account),
        HTTP_AUTHORIZATION=self.token)

升级到 django 1.5,除了与 HTTP PUT 相关的测试外,所有测试都通过了 在调查问题时发现这个@https://docs.djangoproject.com/en/dev/releases/1.5/#options-put-and-delete-requests-in-the-test-client

If you were using the data parameter in a PUT request without a content_type, you must encode your data before passing it to the test client and set the content_type argument.

因此,更新我的测试以反射(reflect)此更改并尝试执行以下操作,但仍然获得 http 415 而不是 http 200

from django.test.client import MULTIPART_CONTENT, BOUNDARY, encode_multipart
self.client.put('/core/accounts/%s/'% self.account.id,
            data = encode_multipart(BOUNDARY, prepare_dict(self.account)),
                content_type=MULTIPART_CONTENT,
        HTTP_AUTHORIZATION=self.token)

知道我错过了什么吗? P.S:所有功能都可以从 django-rest-framework 内置的 web UI 正常运行

最佳答案

您绝对是在正确的轨道上 - 在这种情况下,中断测试肯定是由于 Django 对测试客户端的 PUT 行为的更改。

你的修复看起来对我来说也是正确的。 415 是“不支持的媒体类型”响应,这意味着请求内容类型不是为 View 配置的任何解析器都可以处理的内容。

通常在这种情况下,那是因为忘记设置请求的内容类型,但看起来您已将其正确设置为 multipart/form-data;边界=...

需要仔细检查的事情:

  • response.data 显示错误详细信息的具体内容是什么?
  • 您在 DEFAULT_PARSER_CLASSES 设置中配置了什么(如果有),或者您在 View 属性 parser_classes 上设置了什么(如果有)?<
  • 确保测试中的 content_type 没有拼写错误(即使它在这里是正确的)。

编辑:

感谢您的评论 - 一切都清楚了。您只安装了 JSON 解析器,但您正在尝试发送表单编码数据。您应该:

  • FormParserMultiPartParser 添加到您的设置/ View 中,以便它支持表单编码。 (另请注意,默认的 DEFAULT_PARSER_CLASSES 设置确实包含它们,因此如果您根本不设置任何内容,它会按预期工作)

或者

  • 使用 json 编码对请求进行编码,而不是表单编码... data=json.dumps(prepare_dict(self.account)), content_type='application/json' 在你的测试用例中。

关于django-rest-framework http 在 django 1.5 上以 415 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153048/

相关文章:

javascript - HTML 5 下载属性在 Safari 浏览器中不起作用

python - Django 数据库缓存

python - Django休息框架: Paginaion in detail view breaks when default ordering field is nullable

django - drf如何序列化manytomany字段

python - django 测试文件下载 - "ValueError: I/O operation on closed file"

python - 如何将主键传递给 url 以编辑有关对象的信息?

python - 似乎无法使用 python 检索 Stripe 电荷

django - 我如何在 django-rest-framework 中制作 'view_count'?

django - 升级到 django-rest-framework 3 后出现 UnicodeDecodeError

python - pbkdf2_hmac 在 django 中需要很长时间