sanic:读、写、删除cookies

简介:cookie是保存在用户浏览器中的数据片段。sanic可以读写cookie,cookie存储为键值对。

读取 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。

浏览器内查询cookies:

图片

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 快速开始 在安装Sanic之前,让我们一起来看看Python在支持异步的过程中,都经历了哪些比较重大的更新。 首先...
    hugoren阅读 20,001评论 0 23
  • 1. 入门 Sanic 是一款类似Flask的Web服务器,它运行在Python 3.5+上。 除了与Flask功...
    JasonJe阅读 14,140评论 4 37
  • typora-copy-images-to: ipic [TOC] 快速开始 在安装Sanic之前,让我们一起来看...
    君惜丶阅读 14,258评论 3 18
  • 安装Nginx:yum install -y nginxsystemctl start nginxsystemct...
    碧潭飘雪ikaros阅读 756评论 0 1
  • 会话定义 从打开浏览器访问一个网站,到关闭浏览器结束此次访问,称之为一次会话 HTTP协议是无状态的,导致会话状态...
    JuliusL阅读 173评论 0 0

友情链接更多精彩内容