2011-10-31 14 views

回答

6

響應不會決定url,請求會。

該響應爲您提供響應的內容,而不是它的網址。

+0

但是,如果有重定向,請求不知道。 –

+1

@Joseph Turian:當然可以,它位於引用標頭中:'request.META ['HTTP_REFERER']'。 –

+0

@JosephTurian:請求是從客戶端讀取數據,響應是將數據發送到客戶端。你不能告訴客戶他的網址是什麼,因爲他已經給了你這些數據。你可以告訴客戶重定向到一個不同的頁面。 – Wolph

6

這是舊的,但我在做單元測試時碰到類似的問題。以下是我如何解決問題。

您可以使用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) 
+0

我很想知道投票結果是什麼。 – pyrospade

+0

我在這裏試圖找出有關響應的路徑。但它似乎並不像'HttpResponse'這樣的方法叫做'request'或'redirect_chain'。反向工程雖然獲得網址。 – Jonathan

+0

忘記'follow = True'確實是一件非常糟糕的事情。你沒有,我做過。 https://code.djangoproject.com/ticket/10971 – aliteralmind

相關問題