您如何看待这样的解决方案?:
user_router = APIRouter(
prefix="/user", tags=["users"]
)
user_router.tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
}
]
我正在以这种方式扩展 APIRouter 类。然后,当添加所有路由器时,我将使用该功能并连接标签。
def collect_openapi_tags(*routers):
tags = []
for router in routers:
if hasattr(router, 'tags_metadata'):
tags.extend(router.tags_metadata)
return tags
app = FastAPI
app.openapi_tags = collect_openapi_tags(user_router)
可怕的是ApiRouter类并不暗示tags_metadata参数的存在。这种方法有立足之地吗?
我一直在寻找类似的解决方案,但没有找到。
您在 FastAPI 中向
APIRouter
添加标签的方法很有创意,但并不完全传统,因为 APIRouter
类本质上不支持 tags_metadata
参数。但是,您的方法仍然可以进行一些修改,以确保它与 FastAPI 的现有结构良好集成。
这里有一个改进的方法:
from fastapi import APIRouter, FastAPI
# Define the APIRouter with tags
user_router = APIRouter(
prefix="/user",
tags=["users"]
)
# Add routes to the user_router
@user_router.get("/")
async def get_users():
return [{"user_id": 1, "username": "user1"}]
# Function to collect OpenAPI tags
def collect_openapi_tags(*routers):
tags = []
for router in routers:
if hasattr(router, 'tags_metadata'):
tags.extend(router.tags_metadata)
return tags
# Create the FastAPI app
app = FastAPI()
# Include the router
app.include_router(user_router)
# Manually add the tags metadata
app.openapi_tags = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
}
]
# Customize the OpenAPI schema
@app.on_event("startup")
def customize_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = app.openapi()
openapi_schema["tags"] = app.openapi_tags
app.openapi_schema = openapi_schema
return app.openapi_schema