Cookies
# Cookies
Cookies 是存储在用户浏览器内部的一些数据。Sanic 可以读取和写入存储为键值对的 cookie。
# 读取 Cookies
可以通过Request
对象的cookies
字典来访问用户的 cookies。
from sanic.response import text
@app.route("/cookie")
async def test(request):
test_cookie = request.cookies.get('test')
return text("Test cookie set to: {}".format(test_cookie))
1
2
3
4
5
6
2
3
4
5
6
# 写入 Cookies
在返回响应时,可以在Response
对象上设置 cookies。
from sanic.response import text
@app.route("/cookie")
async def test(request):
response = text("There's a cookie up in this response")
response.cookies['test'] = 'It worked!'
response.cookies['test']['domain'] = '.gotta-go-fast.com'
response.cookies['test']['httponly'] = True
return response
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 删除 Cookies
可以通过语义或明确的方式删除 cookies。
from sanic.response import text
@app.route("/cookie")
async def test(request):
response = text("Time to eat some cookies muahaha")
# This cookie will be set to expire in 0 seconds
del response.cookies['kill_me']
# This cookie will self destruct in 5 seconds
response.cookies['short_life'] = 'Glad to be here'
response.cookies['short_life']['max-age'] = 5
del response.cookies['favorite_color']
# This cookie will remain unchanged
response.cookies['favorite_color'] = 'blue'
response.cookies['favorite_color'] = 'pink'
del response.cookies['favorite_color']
return response
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
可以在响应的 cookies 中设置以下有效参数:
expires
(datetime): cookies 在客户端浏览器上的过期时间。path
(string): cookie 使用的子 URL。默认为/
。comment
(string): 注释(元数据)。domain
(string): cookie 有效的指定域名。明确指定的域名必须始终以.
开头。max-age
(number): cookie 可以存活的最大秒数。secure
(boolean): 指定 cookie 是否只能通过 HTTPS 发送。httponly
(boolean): 指定 cookie 是否不能被 JavaScript 读取。
编辑 (opens new window)
上次更新: 2023/09/07, 12:09:00