如何设置嵌入特殊非HTTP URL中的URL的CacheControl(Python/Django)

2024-09-30 02:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

背景:

在我的Django viewform_valid方法中,我通过字符串连接构建一个URL。假设所说的URL是http://example.com/uuid,其中uuid是传递给这个form_valid方法的POST变量。你知道吗

在这个方法中,我接下来将构造一个定制的HttpResponse对象,它将导致一个非http的url,即nonhttp_url = "sms:"+phonenumber+"?body="+bodybody包含一些文本和我之前通过字符串连接形成的url(例如“转到这个url:[url]”)。phonenumber是任何合法的手机号码。你知道吗

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

问题:

如何确保通过上面的str连接形成并传递到非http URL的body部分的URL Cache-Control设置为no-cache?实际上,我还想要no-storemust-revalidate。类似地,我还需要将Pragma设置为no-cacheExpires设置为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

Tags: 方法noselfformhttpurlgetbody
1条回答
网友
1楼 · 发布于 2024-09-30 02:30:46

我想你会像对待HTTP网址那样做吗?您可以通过using the response as a dictionary设置头,就像您设置Location头一样。在本例中,添加如下行:response['Vary'] = '*'。你知道吗

为了方便起见,可以使用^{}添加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

相关问题 更多 >

    热门问题