• FastAPI大型目录程序设计


    一、目录结构分析

    FastAPI提供了一个类似Flask的Blueprints功能的工具,它可以在保持灵活性的同时构建应用程序。比如:

    .
    ├── app                  # 「app」是一个 Python 包
    │   ├── __init__.py      # 这个文件使「app」成为一个 Python 包
    │   ├── main.py          # 「main」模块,例如 import app.main
    │   ├── dependencies.py  # 「dependencies」模块,例如 import app.dependencies
    │   └── routers          # 「routers」是一个「Python 子包」
    │   │   ├── __init__.py  # 使「routers」成为一个「Python 子包」
    │   │   ├── items.py     # 「items」子模块,例如 import app.routers.items
    │   │   └── users.py     # 「users」子模块,例如 import app.routers.users
    │   └── internal         # 「internal」是一个「Python 子包」
    │       ├── __init__.py  # 使「internal」成为一个「Python 子包」
    │       └── admin.py     # 「admin」子模块,例如 import app.internal.admin

       假设现在有这样的一个项目,一个Web项目有前台是Vue项目,那么它需要后台提供接口,那么可以将前台的所有接口内容写在routers子包中;另外可能还有一个后台管理的系统,那么它的接口可以使用internal子包来进行管理。

      子包中的每一个模块需要解耦开,此时可以使用APIRouter进行管理,可以理解为小型的FastAPI应用,然后将各个部分组合到FastAPI主体上即可。

    二、APIRouter

     在routers子包中,针对前台不同功能,后台分别有不同的接口模块与之对应,比如items.py与users.py:

    • items.py
    from fastapi import APIRouter, Depends
    from dependencies import get_query_token
    
    router = APIRouter(
        prefix="/items",  # 前缀只在这个模块中使用
        tags=["items"],
        dependencies=[Depends(get_query_token)]
    )
    
    
    @router.get("/")
    async def read_items():
        result = [
            {"name": "apple"},
            {"name": "pear"}
        ]
        return result
    • users.py
    from fastapi import APIRouter
    
    router = APIRouter()
    
    
    @router.get("/users/", tags=["users"])
    async def read_user():
        return [{"username": "zhangsan"}, {"username": "lisi"}]
    
    
    @router.get("/users/me", tags=["users"])
    async def read_user_me():
        return {"username": "zhangsan"}

    后台功能接口admin.py:

    from fastapi import APIRouter
    
    router = APIRouter(
        prefix="/manage"
    )
    
    
    @router.get("/menus")
    async def get_menus():
        return [{"title": "用户管理"}]

    三、FastAPI主体整合

    上述的各个模块需要整合到FastAPI主体上,main.py:

    from fastapi import FastAPI, Depends
    from internal import admin
    from routers import items, users
    import sys
    import os
    
    sys.path.append(os.path.join(os.path.dirname(__file__))) #防止相对路径导入出错
    
    app = FastAPI()
    
    # 将其余单独模块进行整合
    app.include_router(users.router)
    app.include_router(items.router)
    app.include_router(
        admin.router,
        prefix="/admin",
        tags=["admin"]
    )
    
    
    @app.get("/")
    async def root():
        return {"message": "Application..."}

    当然还有一些依赖项要使用,对于全局或者局部依赖项可以写入到dependencies.py文件中:

    from fastapi import HTTPException
    
    
    async def get_query_token(x_token: str):
        if x_token != "secret-token":
            raise HTTPException(status_code=400, detail="no secret-token...")

    当完成这些,可以进行项目启动:

    uvicorn main:app --reload

    查看交互文档:

    作者:iveBoy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Python-Matplotlib 12 多图figure
    Python-Matplotlib 11 子图-subplot
    Python Day16
    Python Day15
    Python Day13-14
    Python Day12
    Python Day11
    Python Day9-10
    Python Day8
    Python Day8
  • 原文地址:https://www.cnblogs.com/shenjianping/p/14874390.html
Copyright © 2020-2023  润新知