前后端知识库 前后端知识库
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
首页
    • JavaScript
    • React
    • Vue
  • Python
  • Sanic
  • Linux
  • Ansible
归档
GitHub (opens new window)
  • Sanic

    • 开始
    • Routing
    • 请求数据
    • 响应
    • 静态资源
    • 异常
    • 中间件 和 监听器
    • 蓝图
    • WebSocket
    • 配置
    • Cookies
      • 读取 Cookies
      • 写入 Cookies
      • 删除 Cookies
    • 处理装饰器
    • 流
    • 基于类的视图
    • 自定义协议
    • SSL 例子
    • 日志
    • 测试
    • 部署
    • 扩展
    • 贡献
    • API Reference
  • Python

  • backend
  • Sanic
devin
2023-09-07

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

# 写入 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

# 删除 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

可以在响应的 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
配置
处理装饰器

← 配置 处理装饰器→

Theme by Vdoing | Copyright © 2023-2023 devin | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式