首先感谢您的出色工作,我喜欢使用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而不是通过标头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源代码。
感谢您提供任何信息!
from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')