假设我有一个Django响应对象。
我想找到URL(位置)。 然而,响应头实际上没有Location或Content-Location字段。
如何从这个响应对象中确定它正在显示的URL?
假设我有一个Django响应对象。
我想找到URL(位置)。 然而,响应头实际上没有Location或Content-Location字段。
如何从这个响应对象中确定它正在显示的URL?
虽然这篇文章有些年头,但我在进行单元测试时遇到了类似的问题。这是我解决问题的方法:
你可以使用 response.redirect_chain
或者 response.request['PATH_INFO']
获取重定向 URL。
同时查看文档: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)
响应并不决定URL,请求才是。
响应只提供响应内容,而不是其URL。
request.META ['HTTP_REFERER']
。 - Daniel Roseman
HttpResponse
没有叫做request
或者redirect_chain
的方法。不过,reverse
可以用于获取 URL。 - Jonathanfollow=True
真的很糟糕。你没有写,我却写错了。https://code.djangoproject.com/ticket/10971 - aliteralmindPATH_INFO
不准确。即使在 URL 中没有设置端口,它也会将端口设置为 80,因此,这不是重建 URL 的确定方法。 - pupeno