• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
秋天的童话
梦想从此启航
博客园    首页    新随笔    联系   管理    订阅  订阅

python3的模块FastAPI,APIRouter

FastAPI 将依赖项的值从include_router传递给路由 FastAPI

依赖项和include_router

在FastAPI中,依赖项是一种重要的机制,用于处理从请求到响应的整个过程中所需的各种依赖关系,例如数据库连接、身份验证等。依赖项可以被注入到请求处理函数中,并在执行时提供所需的值。在FastAPI中,我们可以使用Depends装饰器来定义这些依赖项。

而include_router函数是FastAPI中的一种方式,用于将子路由包含到主路由中。通过include_router,我们可以将不同的路由分组,并在需要时将它们添加到主路由中。

实例1:

import uvicorn
from fastapi import FastAPI,APIRouter

router = APIRouter()
#router = APIRouter(prefix='/add')   ###prefix定义在router中
app = FastAPI()

# 绑定路由和视图函数
@app.get("/")
def index():
    return {"msg": "fastapi测试成功"}

# 异步 后面基本会用异步 速度快
@router.get("/numbers")
async def A():
    return {"msg": "we are adding numbers"}

# 同步
@router.get("/strings")
def B():
    return {"msg": "we are adding strings"}

### 动态路径 和 Flask 不同,Flask 是使用 <>,而 FastAPI 使用 {}
@router.get("/{item_id}")
def C(item_id):
    return {"msg": "we are adding {}".format({item_id})}

app.include_router(router,prefix='/add')
#app.include_router(router)     ###prefix定义在router中

if __name__ == "__main__":
    uvicorn.run(app,host="0.0.0.0",port=8000)
View Code

 

在include_router中传递依赖项的值给路由

在某些情况下,我们可能需要在include_router中访问依赖项的值,并将它们传递给子路由中的请求处理函数。为了实现这一点,我们可以使用Dependency类来注入依赖项的值,并将它们作为参数传递给请求处理函数。

实例2:

from fastapi import FastAPI,APIRouter,Depends

router = APIRouter()
app = FastAPI()

async def get_current_user():
    # 获取当前用户的逻辑
    return {"username": "Alice"}

async def get_db_connection():
    # 获取数据库连接的逻辑
    return "database_connection"

# 异步 后面基本会用异步 速度快
@router.get("/users")
async def A(current_user: dict = Depends(get_current_user)):
    return current_user

### 动态路径 和 Flask 不同,Flask 是使用 <>,而 FastAPI 使用 {}
@router.get("/{item_id}")
async def C(item_id: int, db_connection: str = Depends(get_db_connection)):
    return {"item_id": item_id, "db_connection": db_connection}

app.include_router(router,prefix='/add', dependencies=[Depends(get_current_user), Depends(get_db_connection)])

if __name__ == "__main__":
    uvicorn.run(app,host="0.0.0.0",port=8000)
View Code

 

在上面的示例中,定义了两个依赖项函数get_current_user和get_db_connection。它们分别返回当前用户的信息和数据库连接。然后,我们使用APIRouter创建一个路由器,并在该路由器中定义了两个路由,分别处理/users/me和/users/{user_id}的请求。

在include_router函数中,我们将这两个依赖项函数作为dependencies参数传递给了该函数。这样,在子路由中的请求处理函数中,我们就可以直接使用这两个依赖项的值了。

例如,通过访问/users/me路由,我们可以获得当前用户的信息。而通过访问/users/{user_id}路由,我们可以获得指定用户ID的信息以及数据库连接。

这样,我们就成功地将依赖项的值从include_router传递给了路由。

 

FastAPI FastAPI事件处理程序

事件处理程序是当某个确定的事件发生时要执行的功能。在FastAPI中,有两个这样的事件 - 启动 和 关闭。 FastAPI的应用程序对象有一个 on_event() 装饰器,使用这些事件之一作为参数。当相应的事件发生时,与该装饰器注册的函数被触发。

启动事件发生在开发服务器启动之前,注册的函数通常用于执行某些初始化任务,建立与数据库的连接等。关闭事件的事件处理程序在应用程序关闭前被调用。

例:

from fastapi import FastAPI
import datetime
app = FastAPI()
@app.on_event("startup")
async def startup_event():
   print('Server started :', datetime.datetime.now())
@app.on_event("shutdown")
async def shutdown_event():
   print('server Shutdown :', datetime.datetime.now())
做人一定要靠自己
posted @ 2023-10-13 18:01  凯-子  阅读(969)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3