Django Cookies,我该怎么设置? [英] Django Cookies, how can I set them?

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

问题描述

我有一个网站根据访问者选择的位置
显示不同的内容。例如:用户输入55812作为zip。我知道
城市和区域lat / long。那就是向他们提供他们的内容相关的
给该地区。我的问题是如何将它存储在cookie中,以便
返回时不需要始终输入邮政编码?

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?

我看到它是如下:


  1. 根据他们的区域设置持久性cookie。

  2. 当他们返回读取cookie时,邮政编码。

  3. 根据Cookie中的邮政编码来收回内容。

似乎找到任何关于设置cookie的可靠信息。任何
帮助非常感谢。

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

推荐答案

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

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

更新:检查@Peter的回答下面的内置解决方案: https://stackoverflow.com/a/5575578/174027

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

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