应用场景:当我们使用fastapi框架后,不局限app是单个,这个时候我们就要集成多个app服务来健壮我们的web服务,换句话说,就是指将视图函数分文件处理,我们要分场景如下:
uvicorn main:app --reload (类似入口文件main.py不止一个 )
APIRouter 就给我们提供了在多个文件中注册路由的功能。多应用程序管理蓝图APIRouter
详细:
可以看到 有两个应用服务 分别是items,users 分别在 app/routers/xx.py 路径下,
下面代码分别是items.py 和 users.py
from fastapi import APIRouter
router = APIRouter(
prefix="/items",
tags=["items"],
responses={404: {"description":"Not found"}},
)
@router.get("/")
async def read_items():
return "get"
@router.get("/{item_id}")
async def read_item(item_id:str):
return {"name":"2","item_id": item_id}
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/",tags=["users"])
async def read_users():
return [{"username":"Rick"}, {"username":"Morty"}]
@router.get("/users/me",tags=["users"])
async def read_user_me():
return {"username":"fakecurrentuser"}
@router.get("/users/{username}",tags=["users"])
async def read_user(username:str):
return {"username": username}
接下来在“主拖线板” main.py 定义
from app.routers import items, users
from fastapi import FastAPI
from mongoengine import *
connect("test",host='localhost',port=27017)
app = FastAPI()
app.include_router(users.router)#
app.include_router(items.router)
uvicorn app.main:app --reload 即可