如何在Django响应对象中找到位置URL?

Jos*_*ian 7 django httpresponse http-response-codes

假设我有一个Django响应对象.

我想找到URL(位置).但是,响应标头实际上不包含Location或Content-Location字段.

如何从此响应对象中确定它显示的URL?

pyr*_*ade 9

这是旧的,但在进行单元测试时我遇到了类似的问题.这是我解决问题的方法.

您可以使用response.redirect_chain和/或response.request['PATH_INFO']抓取重定向网址.

查看文档! Django测试工具:assertRedirects

from django.core.urlresolvers import reverse
from django.test import TestCase


class MyTest(TestCase)
    def test_foo(self):
        foo_path = reverse('foo')
        bar_path = reverse('bar')
        data = {'bar': 'baz'}
        response = self.client.post(foo_path, data, follow=True)
        # Get last redirect
        self.assertGreater(len(response.redirect_chain), 0)
        # last_url will be something like 'http://testserver/.../'
        last_url, status_code = response.redirect_chain[-1]
        self.assertIn(bar_path, last_url)
        self.assertEqual(status_code, 302)
        # Get the exact final path from the response,
        # excluding server and get params.
        last_path = response.request['PATH_INFO']
        self.assertEqual(bar_path, last_path)
        # Note that you can also assert for redirects directly.
        self.assertRedirects(response, bar_path)
Run Code Online (Sandbox Code Playgroud)


Wol*_*lph 5

响应不会决定URL,请求也是如此.

响应为您提供响应的内容,而不是它的URL.

  • 但是如果有重定向,请求不知道。 (3认同)
  • @Joseph Turian:当然可以,它在引用标头中:`request.META['HTTP_REFERER']`。 (2认同)