【问题标题】:How to specify Accept headers from rest_framework.test.Client?如何指定来自 rest_framework.test.Client 的 Accept 标头?
【发布时间】:2018-12-14 16:13:13
【问题描述】:

我正在尝试设置一个 API 端点,以根据传入请求的 Accept 标头使用 HTML 或 JSON 进行回复。我已经让它工作了,通过 curl 进行测试:

> curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/
{"message":"feedback Hello, world!"}

> curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/
<html><body>
<h1>Root</h1>
<h2>feedback Hello, world!</h2>
</body></html>

不过,我不知道如何使用 APITestCase().self.client 来指定应该接受哪些内容。

我的观点看起来像

class Root(APIView):
    renderer_classes = (TemplateHTMLRenderer,JSONRenderer)
    template_name="feedback/root.html"
    def get(self,request,format=None):
        data={"message": "feedback Hello, world!"}
        return Response(data)

我的测试代码看起来像

class RootTests(APITestCase):
    def test_can_get_json(self):
        response = self.client.get('/feedback/',format='json',Accept='application/json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.accepted_media_type,'application/json')
        js=response.json()
        self.assertIn('message', js)
        self.assertEqual(js['message'],'feedback Hello, world!')

在 response.accepted_media_type 的测试中死亡。这样做的正确方法是什么?我能找到的所有内容都表明格式参数应该足够了。

【问题讨论】:

  • Accept='application/json' 是干什么用的?删除后会发生什么?
  • @DušanMaďar 我希望它将作为标头传递到底层请求中。无论有没有它,测试都会失败,有和没有“headers={'accept':'application/json'}”参数。
  • @Ken4scholars 将其表述为 self.client.get('/feedback/', HTTP_ACCEPT='application/json') 效果很好,我一定看过有关“额外”参数五的文档次。写出来让我接受。

标签: python django testing django-rest-framework


【解决方案1】:

正如here 所说的那样,文档似乎并没有过多地说明如何使用测试客户端向请求中添加标头。但是,extra 参数可以用于此目的,但诀窍是您必须按照 http 标头的外观准确地编写它。所以你应该这样做:

self.client.get('/feedback/', HTTP_ACCEPT='application/json') 

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 2011-04-08
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多