FastAPI教程-路由实现

介绍

路由(Route)就是URL路径 + HTTP方法 + 处理函数,用来接收客户端请求,执行逻辑,返回响应。

实现

通过 装饰器 @app.route('') 实现将 URL 和 函数 进行绑定

支持的 HTTP 请求方法的装饰器

@app.get("/path")      # 查询数据
@app.post("/path")     # 提交创建
@app.put("/path")      # 全量更新
@app.patch("/path")    # 局部更新
@app.delete("/path")   # 删除

例子

@app.get("/")
async def root():
    return {"message": "Hello FastAPI"}

解释:

在上面的代码中 @app.route('/') 表示将 URL根路径 和 root() 函数 进行绑定

案例

提示: 异步

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello FastAPI"}

注意

路由中的 url 必须从 / 开始,如果写成 @app.route('') ,访问:http://127.0.0.1:8000 ,浏览器显示:

{
    "detail": "Not Found"
}

同一 URL 绑定 多个函数

同一 URL 绑定 多个函数,在匹配过程中,至上而下匹配第一个视图函数

@app.get('/hello')
def hello():
    return 'hello'


@app.get('/hello')
def hello2():
    return 'hello2'

浏览器访问网址:http://127.0.0.1:8000/hello 显示的是 hello ,即 hello() 函数的结果

多个URL 绑定一个视图函数

@app.get('/login')
@app.get('/doLogin')
def login():
    return '登录'

浏览器访问网址:http://127.0.0.0:8000/login 和 http://127.0.0.0:8000/doLogin ,都能执行 login() 函数,即:显示的结果是一样的


原文出处:/show_1GW3o7zwfH48.html