Python中如何使用Sanic框架?

@app.route('/get', methods=['GET'], host='example.com')

请问各路大神,这样写路由,限制了 host,该如何写 url,才能访问到呢


Python中如何使用Sanic框架?
1 回复

Sanic基础使用示例

Sanic是一个异步Web框架,核心是处理HTTP请求。下面是一个完整示例:

from sanic import Sanic
from sanic.response import text

app = Sanic("MyApp")

@app.route("/")
async def home(request):
    return text("Hello Sanic!")

@app.route("/user/<name>")
async def user_profile(request, name):
    return text(f"Hello {name}!")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)

关键点说明:

  1. @app.route装饰器定义路由
  2. 处理函数必须是async def异步函数
  3. 路径参数用<name>格式捕获
  4. app.run()启动服务器,debug模式便于开发

处理POST请求:

from sanic.request import Request
from sanic.response import json

@app.post("/api/data")
async def receive_data(request: Request):
    data = request.json  # 获取JSON数据
    return json({"received": data})

路由分组(Blueprint):

from sanic import Blueprint

bp = Blueprint("my_blueprint", url_prefix="/api")

@bp.get("/users")
async def get_users(request):
    return json({"users": ["Alice", "Bob"]})

app.blueprint(bp)  # 注册蓝图

运行:

python app.py
# 或使用sanic命令行
sanic app.app --host=0.0.0.0 --port=8000 --debug

总结:定义路由、写异步处理函数、启动服务。

回到顶部