【发布时间】:2011-12-18 10:39:22
【问题描述】:
假设我有一个 Django 响应对象。
我想查找 URL(位置)。 但是,响应标头实际上并不包含 Location 或 Content-Location 字段。
我如何从这个响应对象中确定它显示的 URL?
【问题讨论】:
标签: django httpresponse http-response-codes
假设我有一个 Django 响应对象。
我想查找 URL(位置)。 但是,响应标头实际上并不包含 Location 或 Content-Location 字段。
我如何从这个响应对象中确定它显示的 URL?
【问题讨论】:
标签: django httpresponse http-response-codes
这是旧的,但我在进行单元测试时遇到了类似的问题。这是我解决问题的方法。
您可以使用response.redirect_chain 和/或response.request['PATH_INFO'] 来获取重定向网址。
也请查看文档! Django Testing Tools: 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)
【讨论】:
HttpResponse 没有称为request 或redirect_chain 的方法。 reverse 适用于获取网址。
follow=True 确实是一件非常糟糕的事情。你没有,我有。 code.djangoproject.com/ticket/10971
PATH_INFO 不准确。即使在 URL 中没有设置端口,它也会将端口设置为 80,因此,这不是重建 URL 的明确方法。
响应不决定 url,请求决定。
响应为您提供响应的内容,而不是它的 url。
【讨论】:
request.META['HTTP_REFERER']。