【问题标题】:How to find the location URL in a Django response object?如何在 Django 响应对象中找到位置 URL?
【发布时间】:2011-12-18 10:39:22
【问题描述】:

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

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

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

【问题讨论】:

    标签: django httpresponse http-response-codes


    【解决方案1】:

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

    您可以使用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 没有称为requestredirect_chain 的方法。 reverse 适用于获取网址。
    • 忘记follow=True 确实是一件非常糟糕的事情。你没有,我有。 code.djangoproject.com/ticket/10971
    • PATH_INFO 不准确。即使在 URL 中没有设置端口,它也会将端口设置为 80,因此,这不是重建 URL 的明确方法。
    【解决方案2】:

    响应不决定 url,请求决定。

    响应为您提供响应的内容,而不是它的 url。

    【讨论】:

    • 但是如果有重定向,请求不知道。
    • @Joseph Turian:确实如此,它在引荐来源标题中:request.META['HTTP_REFERER']
    • @JosephTurian:请求是从客户端读取数据,响应是向客户端发送数据。你不能告诉客户他在哪个网址,因为他已经给了你这些数据。不过,您可以告诉客户端重定向到不同的页面。
    • 因此,请求的 URL(如果是在重定向之后)将永远丢失。客户端不会将其保留为状态,也不会将其添加到响应中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2016-12-31
    • 2014-03-02
    • 2014-06-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多