我有一个网站根据访问者选择的位置显示不同的内容。 例如:用户输入55812作为zip。 我知道什么城市和地区lat / long。 那就是并且给他们他们与该地区有关的内容。 我的问题是如何将它存储在cookie中,以便在返回时不需要始终输入邮政编码?
我看到如下:
根据他们的区域设置持久性cookie。 当他们返回阅读cookie,抓住邮政编码。 根据Cookie中的邮政编码返回内容。我似乎找不到有关设置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?
I see it as follows:
Set persistent cookie based on their area. When they return read cookie, grab zipcode. 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.
最满意答案
这是一个帮助器设置一个持久的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)发送响应之前,请使用以下代码。
def view(request): response = HttpResponse("hello") set_cookie(response, 'name', 'jujule') return response更新 :检查@Peter下面的内置解决方案: https : //stackoverflow.com/a/5575578/174027
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 responseUPDATE : check Peter's answer below for a builtin solution :
更多推荐
发布评论