【发布时间】:2018-06-24 19:29:30
【问题描述】:
首先感谢您的出色工作,我喜欢使用 Django REST 框架来自动化 Web API 端点创建的所有样板。
我在使用 rest_framework.test.RequestsClient 测试一些 API 端点时遇到了问题。我找到了解决方案,但现在我想知道如何才能更快地找到解决方案。
问题出在这里:我尝试使用以下代码测试 PUT API 端点(受请求文档启发,通过自定义标头指定内容类型: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': 'Unsupported media type "application/octet-stream" in request.'}
解决方案: 嗯,好的,似乎没有考虑指定的内容类型。在 google 上搜索后,我看到了这个 stackoverflow 帖子,通过 put 方法的 content_type kwarg 指定了内容类型: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 可以通过标头 kwarg 指定内容类型:
69 if 'content-type' in request.headers:
70 kwargs['content_type'] = request.headers['content-type']
我很累,我可能错过了一些东西。另外我没有深入研究 DRF 源代码。
感谢您提供任何信息!
【问题讨论】:
标签: rest django-rest-framework http-headers python-requests content-type