扩展应用: 构建大型应用
拓展规模:构建更大的应用程序
Section titled “拓展规模:构建更大的应用程序”将所有代码都写在一个 main.py 文件中,对于一个“Hello World”应用来说尚可接受,但随着应用程序的增长,这会变得难以管理。想象一下一本所有章节都写在一页无限长的纸上的书,阅读起来是不是很困难?在本章中,我们将学习如何将代码组织成专业的目录结构。
专业的目录结构
Section titled “专业的目录结构”我们应该将逻辑分离到不同的模块中。FastAPI 中一个常见的模式是为应用程序逻辑设立一个专门的文件夹(包),并在其中包含一个用于存放路由(routers)的子目录,用于组织端点(endpoint)。
.├── app│ ├── __init__.py│ ├── main.py # The entry point│ ├── dependencies.py # Shared dependencies│ └── routers # Separate modules for path operations│ ├── __init__.py│ ├── items.py # Endpoints related to items│ └── users.py # Endpoints related to users使用 APIRouter
Section titled “使用 APIRouter”APIRouter 类是实现这种分离的关键。它的工作方式与 FastAPI 类完全相同(你可以使用 @router.get 等装饰器来定义路径),但它设计用于稍后被包含在主应用程序中。你可以把它想象成一个“迷你应用程序”。
以下是 app/routers/users.py 的示例:
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])def read_users(): return [{"username": "Rick"}, {"username": "Morty"}]
@router.get("/users/me", tags=["users"])def read_user_me(): return {"username": "fakecurrentuser"}将路由集成到主应用程序中
Section titled “将路由集成到主应用程序中”定义好路由后,你需要将它们整合到 app/main.py 中。我们使用 .include_router() 方法。
你也可以借此机会为特定路由定义全局配置,例如 URL prefix(前缀)或 tags(标签),用于自动生成文档。
from fastapi import FastAPIfrom .routers import users, items
app = FastAPI()
# Include the users router# 引入 users 路由# All paths in 'users' will naturally start with /users due to the router definition,# 由于路由定义,'users' 中的所有路径自然会以 /users 开头,# but we can also enforce prefixes here if we want.# 但我们也可以在这里强制设置前缀。app.include_router(users.router)
# Include the items router with a prefix# 引入带有前缀的 items 路由# If items.py has a path "/", it becomes "/items/"# 如果 items.py 有一个路径 "/",它将变为 "/items/"app.include_router( items.router, prefix="/items", tags=["items"], responses={404: {"description": "Not found"}},)通过这种方式组织应用程序,多个开发人员可以同时在不同模块上工作而不会产生冲突,并且你的代码将保持清晰和易于导航。