如何设置嵌入在特殊非http URL中的URL的Cache-Control(Python / Django)

时间:2016-02-13 04:58:55

标签: python html django url httpresponse

背景

在我的Django form_valid的{​​{1}}方法中,我正在通过字符串连接构建一个网址。想象一下,所述URL为$.ajax,其中view是传递给此uuid方法的POST变量。

在这种方法中,接下来我将构建一个自定义form_valid对象,该对象将导致非http 网址为HttpResponsenonhttp_url = "sms:"+phonenumber+"?body="+body包含一些文字和我之前通过字符串连接形成的网址(例如'转到此网址:body')。 [url]是任何合法的手机号码。

这样构造的phonenumber对象实际上是一个HTML技巧,用于打开手机的本机短信应用程序并预​​先填写电话号码和短信机构。它的常见用法是HttpResponse。我本质上是在调用相同的东西,但是从我的Django视图的<a href="sms:phonenumber?body="+body">Send SMS</a>方法内部。

问题:

如何确保我通过上面的str连接形成并传入非http网址的form_valid部分的网址body设置为Cache-Control?实际上,我还想要no-cacheno-store。同样,我还需要must-revalidate设置为Pragmano-cache设置为Expires0设置为Vary

当前代码:

*

1 个答案:

答案 0 :(得分:0)

我认为你会像对待HTTP网址那样做吗?您可以按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