Django Cookies,我如何设置它们? [英] Django Cookies, how can I set them?

查看:94
本文介绍了Django Cookies,我如何设置它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,根据访问者选择的位置
显示不同的内容。例如:用户在邮件中输入55812。我知道什么
城市和地区纬度/长。那就是给他们他们的内容相关的
到那个区域。我的问题是如何存储在一个cookie中,这样
当他们返回时,他们不需要总是输入他们的邮政编码?



我看到它

  • 当他们返回读取的Cookie时,抓取邮政编码。

  • 根据其Cookie中的邮政编码返回内容。

  • t似乎找到任何有关设置cookie的固体信息。任何
    帮助是非常感谢。

    解决方案

    这是一个设置持久性cookie的帮助器:

      import datetime 

    def set_cookie(response,key,value,days_expire = 7):
    如果days_expire为None:
    max_age = 24 * 60 * 60 #one year
    else:
    max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(datetime.datetime.utcnow()+ datetime.timedelta (seconds = max_age),%a,%d-%b-%Y%H:%M:%S GMT)
    response.set_cookie(key,value,max_age = max_age,expires = expires,domain = settings.SESSION_COOKIE_DOMAIN,secure = settings.SESSION_COOKIE_SECURE或None)

    在发送回复之前使用以下代码。

      def view(request):
    response = HttpResponse(hello)
    set_cookie ,'name','jujule')
    返回响应

    UPDATE :检查@Peter的答案如下内置解决方案: http://stackoverflow.com/a/5575578/174027


    I have a web site which shows different content based on a location the visitor chooses. e.g: User enters in 55812 as the zip. I know what city and area lat/long. that is and give them their content pertinent to that area. My question is how can I store this in a cookie so that when they return they are not required to always enter their zip code?

    I see it as follows:

    1. Set persistent cookie based on their area.
    2. When they return read cookie, grab zipcode.
    3. Return content based on the zip code in their cookie.

    I can't seem to find any solid information on setting a cookie. Any help is greatly appreciated.

    解决方案

    This is a helper to set a persistent cookie:

    import datetime
    
    def set_cookie(response, key, value, days_expire = 7):
      if days_expire is None:
        max_age = 365 * 24 * 60 * 60  #one year
      else:
        max_age = days_expire * 24 * 60 * 60 
      expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
      response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)
    

    Use the following code before sending a response.

    def view(request):
      response = HttpResponse("hello")
      set_cookie(response, 'name', 'jujule')
      return response
    

    UPDATE : check @Peter answer below for a builtin solution : http://stackoverflow.com/a/5575578/174027

    这篇关于Django Cookies,我如何设置它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆