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

    • 开始
    • Routing
    • 请求数据
    • 响应
      • 富文本
      • HTML
      • JSON
      • 文件
      • 流
      • 文件流
      • 重定向
      • Raw
      • 修改 头部 或 状态码
    • 静态资源
    • 异常
    • 中间件 和 监听器
    • 蓝图
    • WebSocket
    • 配置
    • Cookies
    • 处理装饰器
    • 流
    • 基于类的视图
    • 自定义协议
    • SSL 例子
    • 日志
    • 测试
    • 部署
    • 扩展
    • 贡献
    • API Reference
  • Python

  • backend
  • Sanic
devin
2023-09-07

响应

# 响应

使用 sanic.response 模块的函数创建响应。

# 富文本

from sanic import response


@app.route('/text')
def handle_request(request):
    return response.text('Hello world!')
1
2
3
4
5
6

# HTML

from sanic import response


@app.route('/html')
def handle_request(request):
    return response.html('<p>Hello world!</p>')
1
2
3
4
5
6

# JSON

from sanic import response


@app.route('/json')
def handle_request(request):
    return response.json({'message': 'Hello world!'})
1
2
3
4
5
6

# 文件

from sanic import response


@app.route('/file')
async def handle_request(request):
    return await response.file('/srv/www/whatever.png')
1
2
3
4
5
6

# 流

from sanic import response

@app.route("/streaming")
async def index(request):
    async def streaming_fn(response):
        response.write('foo')
        response.write('bar')
    return response.stream(streaming_fn, content_type='text/plain')
1
2
3
4
5
6
7
8

# 文件流

对于大文件,会结合以上的 文件 和 流 实现。

from sanic import response

@app.route('/big_file.png')
async def handle_request(request):
    return await response.file_stream('/srv/www/whatever.png')
1
2
3
4
5

# 重定向

from sanic import response


@app.route('/redirect')
def handle_request(request):
    return response.redirect('/json')
1
2
3
4
5
6

# Raw

不对 body 编码的响应

from sanic import response


@app.route('/raw')
def handle_request(request):
    return response.raw(b'raw data')
1
2
3
4
5
6

# 修改 头部 或 状态码

要修改头部或状态码,传递 headers 或 status 参数给这些函数:

from sanic import response


@app.route('/json')
def handle_request(request):
    return response.json(
        {'message': 'Hello world!'},
        headers={'X-Served-By': 'sanic'},
        status=200
    )
1
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2023/09/07, 12:09:00
请求数据
静态资源

← 请求数据 静态资源→

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