Sanic 下一代 Python Web 服务器/框架,用于编写,部署和扩展生产级 Web 应用程序
介绍
- 目标:提供一种简单且快速,集创建和启动于一体的方法,来实现一个易于修改和拓展的 HTTP 服务
- 特点:简单轻便、灵巧无束、易于拓展
- 运行环境 >= Python3.7
安装
pip install sanic- help
sanic --helphello world
- server.py
from sanic import Sanic
from sanic.response import text
app = Sanic("MyHelloWorldApp")
@app.get("/")
async def hello_world(request):
return text("Hello, world.")方法声明支持 async/await 两种方式:
- 同步方式(
def hello_world)声明 - 异步方式(
async def hello_world)声明
运行
sanic server.appExtensions
pip install sanic-ext- OpenAPI
- CORS 保护
从 v21.12 开始,Sanic 将自动设置 Sanic 扩展,两种方式:
-
app.extend()用于配置 Sanic 拓展 -
app.ext注入到应用程序的扩展实例 -
server.py
from sanic import Sanic
from sanic.response import text
from sanic_ext import Extend
app = Sanic("MyHelloWorldApp")
Extend(app)
@app.get("/")
async def hello_world(request):
return text("Hello, world.")访问 http://localhost:8000/docs 看到 OpenAPI 文档
# Application context
app = Sanic("MyApp")
app.ctx.db = Database()
# App Registry
# ./path/to/server.py
from sanic import Sanic
app = Sanic("my_awesome_server")
# ./path/to/somewhere_else.py
from sanic import Sanic
app = Sanic.get_app("my_awesome_server")
# Configuration
app = Sanic('myapp')
app.config.DB_NAME = 'appdb'
app.config['DB_USER'] = 'appuser'
db_settings = {
'DB_HOST': 'localhost',
'DB_NAME': 'appdb',
'DB_USER': 'appuser'
}
app.config.update(db_settings)