rest - Django REST 框架 RequestsClient 内容类型

首先感谢您的出色工作,我喜欢使用 Django REST 框架来自动化创建 Web API 端点的所有样板。

我在使用 rest_framework.test.RequestsClient 测试一些 API 端点时遇到了问题。我找到了解决方案,但现在我想知道如何更快地找到解决方案。

问题出在这里: 我尝试使用以下代码测试 PUT API 端点(受请求文档的启发,通过自定义 header 指定内容类型:http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers):

from rest_framework.test import RequestsClient 
client = RequestsClient()
headers = {'content-type': 'application/json'}
response = client.put(my_url, json.dumps(my_data), headers=self.headers)

并获得状态 415,详细信息如下:

{'detail': '请求中不支持媒体类型“application/octet-stream”。'}

解决方案: 好吧,似乎没有考虑指定的内容类型。在谷歌上的搜索让我找到了这篇通过 put 方法的 content_type kwarg 指定内容类型的 stackoverflow 帖子:django-rest-framework http put failing with 415 on django 1.5

response = client.put(..., content_type='application/json')

问题:

我怎么能更快地发现支持的指定内容类型的方法是通过 content_type kwarg 而不是通过 headers kwarg?我在这里查看了 DRF 源代码:https://github.com/encode/django-rest-framework/blob/master/rest_framework/test.py并且 DjangoTestAdapter 似乎可以通过 header kwarg 指定内容类型:

69   if 'content-type' in request.headers:
70       kwargs['content_type'] = request.headers['content-type']

我累了,我可能错过了什么。我也没有深入研究 DRF 源代码。

感谢您提供任何信息!

最佳答案

使用来自 DRF 的客户端:http://www.django-rest-framework.org/api-guide/testing/#apiclient

from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')

https://stackoverflow.com/questions/48275326/

相关文章:

git - 如何在 VS Code 中只提交跟踪的文件?

macos - 有没有办法防止 OSX 用数千个 .DS_Store 文件污染我的项目?

google-chrome-extension - 将 Google Chrome 扩展程序限制为选

amazon-web-services - AWS API 网关响应正文模板映射(foreach)

python-3.x - 在 XGBoost 中应用增量学习进行分类设置时出错(python)

spring - @Transactional(read-only = true) 的目的是什么

bazel - 从 bazelrc 选择特定于平台的默认值 --config

php - 使用 PHP Trader 函数的问题 : Call to undefined func

python - 如何将 Spyder 设置为默认程序/应用程序以打开 (.py) Python 文

javascript - 如何从提供 NET::ERR_CERT_AUTHORITY_INVALID