Cookies
cookie是保存在用户浏览器中的数据片段。SANIC可以读写cookie,cookie存储为键值对。
警告
客户可以自由更改cookie。因此,您不能只将登录信息等数据按原样存储在cookie中,因为客户机可以自由更改这些数据。为了确保存储在cookie中的数据不会被客户伪造或篡改,请使用类似的 itsdangerous 对数据进行加密签名。
读取 cookies
用户的cookie可以通过 Request
对象的 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))
写 cookies
返回响应时,可以在 Response
对象。
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
删除cookie
可以从语义上或显式地删除cookie。
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
响应cookie可以设置为字典值,并具有以下可用参数:
expires
(日期时间):客户端浏览器上的cookie过期时间。path
(字符串):应用此cookie的URL的子集。默认值为comment
(字符串):注释(元数据)。domain
(字符串):指定cookie有效的域。显式指定的域必须始终以点开头。max-age
(number):cookie应生存的秒数。secure
(布尔值):指定是否仅通过HTTPS发送cookie。httponly
(布尔值):指定JavaScript是否无法读取cookie。