Django Cookies,我该如何设置它们? [英] Django Cookies, how can I set them?
问题描述
我有一个根据位置显示不同内容的网站访客选择.例如:用户输入 55812 作为 zip.我知道什么城市和地区纬度/经度.也就是说,给他们相关的内容到那个区域.我的问题是如何将其存储在 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?
我是这样看的:
- 根据他们的区域设置持久性 cookie.
- 当他们返回读取的 cookie 时,获取邮政编码.
- 根据 cookie 中的邮政编码返回内容.
我似乎找不到任何关于设置 cookie 的可靠信息.任何非常感谢帮助.
I can't seem to find any solid information on setting a cookie. Any help is greatly appreciated.
推荐答案
UPDATE :检查 Peter 的回答 下面是内置解决方案:
UPDATE : check Peter's answer below for a builtin solution :
这是一个设置持久性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
更新:检查彼得的回答下面的内置解决方案:
UPDATE : check Peter's answer below for a builtin solution :
这篇关于Django Cookies,我该如何设置它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!