Django Cookies,我该怎么设置?(Django Cookies, how can I set them?)

编程入门 行业动态 更新时间:2024-10-24 14:25:12
Django Cookies,我该怎么设置?(Django Cookies, how can I set them?)

我有一个网站根据访问者选择的位置显示不同的内容。 例如:用户输入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 response

UPDATE : check Peter's answer below for a builtin solution :

更多推荐

本文发布于:2023-04-28 03:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我该怎么   Django   Cookies   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!