22. cookie
你的鼓励是我前进的动力,请为我点个赞吧!
cookie是一个存储用户信息的浏览器插件,Sanic同时支持读和写cookie,存储信息的方式为键-值对。
警告⚠️
cookie可以被客户端任意的修改,因此为了信息安全开发者不能将登陆信息存储其中,为了确保客户端的数据不能被修改,可以使用itsdangerous库进行数据的签名加密。
(1) 读取cookie
通过request.cookies.get( )获取cookie的值。
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))
(2) 写入cookie
sanic框架的response对象提供了cookies属性,sanic框架在返回数据时将cookies属性处理成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
(3) 删除cookie
使用del
response.cookies[“键”]进行删除,其实是设置成过期时间为0秒。设置过期时间还可以通过cookies的max-age属性进行设置。
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
cookies还有如下属性可以设置:
名称 | 作用 |
---|---|
expires(datetime) | 过期时间 |
path(string) | 使用cookies的路由 |
comment(string) | 评论 |
domain(string) | 指定cookie的域,使用”.”使用 |
max-age(number) | cookie存活时间 |
secure(boolean) | cookies是否能只能通过Https发送 |
httponly(boolean) | cookies是否能被js读取 |