FastAPI系列教程03:FastAPI路由(router)


在“FastAPI系列02:FastAPI程序结构与生命周期”一节中,我们以宏观的视野分析了FastAPI框架的结构,了解了FastAPI路由系统在FastAPI框架中的重要地位,本节将对FastAPI路由进行展开分析,进一步了解FastAPI的路由规则、路由管理器以及路由的注册和执行过程。

1、路由的注册过程

路由是 Web 应用中的 URL 映射规则。FastAPI 使用装饰器的方式将这些URL 映射规则与指定的路由函数绑定起来,从而完成特定的 HTTP 请求与具体Python 函数响应的连接。
FastAPI 提供了以下几种方式向路由管理器注册路由:

1)使用 FastAPI 实例注册路由

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {
   
   "item_id": item_id, "q": q}
    

说明:
• 使用 @app.get(“/items/{item_id}”) 注册路由
• item_id 是路径参数
• q 是查询参数,默认为 None

2)使用 APIRouter 模块化路由

APIRouter 提供了更好的路由管理方式,便于拆分和复用。

from fastapi import FastAPI, APIRouter

app = FastAPI()
router = APIRouter()

@router.get("/users/{user_id}")
async def read_user(user_id: int):
    return {
   
   "user_id": user_id}

# 将路由挂载到主应用
app.include_router(router, prefix="/api", tags=["Users"])

说明:
• 使用 APIRouter() 创建路由对象
• 使用 include_router() 将路由挂载到主应用
• prefix=“/api” 为路由统一加前缀 /api

3)路由注册装饰器方法

FastAPI 提供了简洁的装饰器方法来定义路由。常用的路由方法包括:
@app.get():处理 GET 请求
@app.post():处理 POST 请求
@app.put():处理 PUT 请求
@app.delete():处理 DELETE 请求
@app.patch():处理 PATCH 请求
@app.options():处理 OPTIONS 请求
@app.head():处理 HEAD 请求

from fastapi import FastAPI

app = FastAPI()

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

@app.post("/items/")
async def create_item(name: str):
    return {
   
   "name": name}

2、路由管理器

在FastAPI中,所有的注册路由都会统一保存到app.routes中,app.routes保存了所有的路由注册信息,包括通过API Router所注册的路由。

使用 app.routes 查看所有路由

from fastapi import FastAPI, APIRouter
app = FastAPI()

# 由FastAPI 实例注册的路由
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {
   
   "item_id": item_id}

@app.post("/items/")
async def create_item(name: str):
    return {
   
   "name": name}

# 由APIRouter 注册的路由 
router = APIRouter()
@router.get("/users/")
async def get_users():
    return [{
   
   "name": "Alice"}, {
   
   "name": "Bob"}]

app.include_router(router)

# 打印所有路由
for route in app.routes:
    print(f"Path: {
     
     route.path}, Methods: {
     
     route.methods}")

如果需要更多的路由信息,比如处理函数的名称、依赖项等,可以通过以下方式获取:

for route in app.routes:
    print
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值