一个最小的应用

from sanic import Sanic
from sanic.response import json

app = Sanic("demo")

@app.get("/")
async def index(request):
    return json({"hello": "world"})

路由参数

@app.get("/post/<slug:str>")
async def detail(request, slug):
    ...

支持 strintfloatpath 等类型。

生命周期

@app.before_server_start
async def setup(app, _):
    # 建表、连接数据库等
    ...

小结

Sanic 的 API 简洁直观,与 asyncio 生态无缝集成,适合构建高性能服务。