2016-02-13 53 views
0

背景:如何設置嵌入一個特殊的非HTTP URL(Python的/ Django的)範圍內的URL的緩存控制

在礦井的一個Django viewform_valid方法,我通過構造URL 字符串連接。想象一下,上述網址爲http://example.com/uuid,其中uuid是傳遞給此form_valid方法的POST變量。

在這種方法中,我接下來將構建一個自定義HttpResponse對象,這將導致一個非HTTP URL,爲nonhttp_url = "sms:"+phonenumber+"?body="+bodybody包含一些文本和我之前通過字符串連接形成的url(例如,'轉到此網址:[url]')。 phonenumber是任何合法的手機號碼。

這樣構造的HttpResponse對象實際上是一個HTML技巧,用於打開手機的本機短信應用程序並預​​先填充電話號碼和短信主體。常見的用法是<a href="sms:phonenumber?body="+body">Send SMS</a>。我本質上是調用同樣的東西,但從我的Django視圖的form_valid方法中。

問題:

如何確保我通過STR串聯上方形成的URL傳遞到非HTTP URL的body部分具有Cache-Control設置爲no-cache?其實我也想要no-storemust-revalidate。同樣,我還需要Pragma設爲no-cache,Expires設爲0Vary設爲*

當前代碼:

class UserPhoneNumberView(FormView): 
    form_class = UserPhoneNumberForm 
    template_name = "get_user_phonenumber.html" 

    def form_valid(self, form): 
     phonenumber = self.request.POST.get("mobile_number") 
     unique = self.request.POST.get("unique") 
     url = "http://example.com/"+unique 
     response = HttpResponse("", status=302) 
     body = "See this url: "+url 
     nonhttp_url = "sms:"+phonenumber+"?body="+body 
     response['Location'] = nonhttp_url 
     return response 

回答

0

我會認爲你這樣做只是因爲你會爲一個HTTP URL?您可以通過using the response as a dictionary來設置標題,就像您使用Location標題一樣。在這種情況下,添加如下行:response['Vary'] = '*'

爲方便起見,您可以使用add_never_cache_headers()添加Cache-ControlExpires標題。

下面是一個例子:

from django.utils.cache import add_never_cache_headers 

class UserPhoneNumberView(FormView): 
    form_class = UserPhoneNumberForm 
    template_name = "get_user_phonenumber.html" 

    def form_valid(self, form): 
     phonenumber = self.request.POST.get("mobile_number") 
     unique = self.request.POST.get("unique") 
     url = "http://example.com/"+unique 
     response = HttpResponse("", status=302) 
     body = "See this url: "+url 
     nonhttp_url = "sms:"+phonenumber+"?body="+body 
     response['Location'] = nonhttp_url 

     # This will add the proper Cache-Control and Expires 
     add_never_cache_headers(response) 

     # Now just add the 'Vary' header 
     response['Vary'] = '*' 
     return response 
+0

是啊,我知道你的意思。但是我在想,當我們這樣做的時候,我們是不是將'no-cache'等*完全*添加到我們構建的'nonhttp url'中?例如,用你寫的代碼,'url'本身(定義爲'url =「http://example.com/」+ unique')沒有設置「Cache-Control」,對吧?我們只設置了它所屬的nonhttp url的'Cache-Control',否?或者我錯過了什麼? –

+0

好吧,'Cache-Control'設置在HTTP響應上,而不是URL上。如果您希望在來自「http://example.com/」+唯一網址的響應中設置標頭,則必須確保該網址返回帶有這些標頭的響應。您無法指定除當前響應之外的響應中的標題。如果你也控制你發送的URL,那應該很容易做到。 – csinchok

+0

我明白你的意思了。 –