[英]Python Setting and Recalling Cookies
Is there any way that I could set a cookie and later recall a variable from that cookie using python?有什么方法可以设置 cookie,然后使用 python 从该 cookie 中调用变量? Like:
喜欢:
> setcookie("prefence","data")
...
> recallcookie("preference")
data
I would prefer not to use libraries that aren't built in, but if necessary, I am fine with using an external library.我不想使用非内置的库,但如果有必要,我可以使用外部库。
I found out myself, using SimpleCookies and the HTTP_COOKIE environmental variable.我发现自己,使用 SimpleCookies 和 HTTP_COOKIE 环境变量。 In the content header, define cookies as normal (SimpleCookies makes this simple).
在内容标题中,正常定义 cookie(SimpleCookies 使这变得简单)。 For example:
例如:
from http import cookies
cookie = cookies.SimpleCookie()
cookie["varname"] = 'value'
print(cookie.output())
Then normal cookie variables can be assigned like so:然后可以像这样分配普通的 cookie 变量:
cookie["varname"] = 'value'
cookie["varname"]["expires"] = "formatted date"
cookie["varname"]["othercookieproperty"] = "othercookieproperty"
To recall them, one can make a Simple Cookie out of the HTTP_COOKIE environmental variable, like so:回想一下,可以从 HTTP_COOKIE 环境变量中创建一个简单的 Cookie,如下所示:
readcookie = cookies.SimpleCookie(os.environ["HTTP_COOKIE"])
print(readcookie["varname"].value)
This would print 'value', the value assigned earlier.这将打印“值”,即之前分配的值。 These can also be called between sessions, until the cookie expires.
这些也可以在会话之间调用,直到 cookie 过期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.