写Web应用(网站等)经常会用到Cookies。Sanic可以读写Cookies,并以key-value(键值对)的方式存储。警告:因为Cookies很容易被客户端修改,所以不能把登录信息直接保存到cookies里面,而是经过加密后再放到cookies。后面我将写一篇用于Sanic加密cookies的文章来介绍在Sanic中使用加密cookies的方法。
读取cookies
用户(客户端)发来的数据都保存在Request
对象里面,其中也包含cookies。通过该对象的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))
写入Cookies
返回响应时,可以吧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
删除cookies
可以在语义上或显式删除Cookie。
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/cookie")
async def test(request):
response = text("Time to eat some cookies muahaha")
# 删除一个不存在的cookie,就会把它的Max-age设置为0
del response.cookies['kill_me']
# 该cookie将在5秒内销毁。
response.cookies['short_life'] = 'Glad to be here'
response.cookies['short_life']['max-age'] = 5
# 还是删除一个不存在的cookies
del response.cookies['favorite_color']
# This cookie will remain unchanged
response.cookies['favorite_color'] = 'blue'
response.cookies['favorite_color'] = 'pink'
# 从cookies字典中移除`favorite_color`键
del response.cookies['favorite_color']
return response
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
通过curl查看一下cookies的情况:
curl -i http://127.0.0.1:8888/cookie
可以看到如下输出:
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Set-Cookie: kill_me=""; Path=/; Max-Age=0
Set-Cookie: short_life="Glad to be here"; Path=/; Max-Age=5
Content-Length: 32
Content-Type: text/plain; charset=utf-8
Time to eat some cookies muahaha
响应的cookies可以像字典那样设置值,有效的键如下:
expire
(类型:datetime):cookie在客户端的浏览器到期时间。path
(类型:string):cookie应用的URL子集。默认为/
。comment
(类型:string):注释(metadata)。domain
(类型:string):指定cookie有效的域。 明确指定的域必须始终以点开头。max-age
(类型:数字):cookie存活的秒数secure
(类型:boolean):指定cookie是否只通过HTTPS发送。httponly
(类型:boolean):指定cookie是否能被Javascript读取。

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...