有勇气的牛排博客

Python后端框架Sanic【持续更新】

有勇气的牛排 435 Python 2023-05-06 00:31:54

1 介绍

1.1 官方介绍

Sanic 是 Python3.7+ Web 服务器和 Web 框架,旨在提高性能。它允许使用 Python3.5 中添加的 async/await 语法,这使得您的代码有效的避免阻塞从而达到提升响应速度的目的。

Sanic 不仅仅是一个 框架,它还是一个 Web 服务器

github: https://github.com/couragesteak/python_web_framework_sanic

教程地址:https://www.couragesteak.com/article/331

1.2 特征

  • 内置极速 web server
  • 生产准备就绪
  • 极高的拓展性
  • 支持 ASGI
  • 简单直观的 API 设计
  • 社区保障

2 快速入门

2.1 Hello World

pip install sanic

快速搭建一个Hello World

from sanic import Sanic, json app = Sanic("my_demo") # http://127.0.0.1:8089 @app.route("/") async def index(request): return json({"code": 1, "msg": "Hello World"}) if __name__ == "__main__": app.run(host="127.0.0.1", port=8089, debug=True) # app.run(host="0.0.0.0", port=80)

注意:

  • 每个请求都可以使用 同步/异步的方式进行声明,但更推荐统一使用异步。

    • def index()
    • async def index()
  • request对象采用了显示传递,作为响应函数的第一个参数,而其他框架需要导入上下文。

  • 在Sanic中,必须使用 Response或继承子Response的类型作为响应类型

2.3 应用程序上下文 Application context

大多数程序都需要夸代码库的共享/重用数据或对象,最常见的就是数据库连接。

在Sanic V21.3 版本以前,是将属性附加到应用程序实现的:

app = Sanic("MyApp") app.db = Database()

到了 V21.3版本,官方引入了 应用级上下文对象,这有效避免了命名成图的潜在问题。

app = Sanic("MyApp") app.ctx.db = Database()

实例

@app.middleware("request") async def inject_session(request): # 写入 request.ctx.db_name = "test" # 读取 db = request.db_name.db

2.3 请求 Request

2.3.1 请求体 json/raw/form/uploaded

1、json

curl 127.0.0.1:8000 -d '{"name": "couragesteak"}'
name = await request_post_arg(request, "name")

2、raw

请求正文中原始字节

2.2 Sanic 扩展

单独安装方法

pip install sanic[ext] pip install sanic-ext

从 V21.12开始,Sanic将自动设置Sanic扩展。

  • app.extend() :用于配置Sanic扩展
  • app.ext :注入到应用程序的扩展实例

留言

专栏
文章
加入群聊