最近搞了一个API综合服务平台,本来准备继续用Django开发的,但是在实际开发中,发现使用orm并不多,所以转向FastAPI。
因为API比较多,所以需要分不同的路由去写,而FastAPi刚好也提供了这样的方法:APIRouter类,正常使用是下面这样的。
首先在路由文件夹中写好路由以及视图函数
# app/routers/item.py
router = APIRouter(
prefix='/item'
)
@router.get('item')
async def get_item():
pass
然后在main.py中引入并注册路由
# app/main.py
from fastapi import FastAPI
from app.routers import item
app = FastAPI()
app.include_router(item.router)
这样看起来很方便,但是当我routers包中还分了development、life等等其他包,而这些包中才是其对应的路由的时候,每次新增一个路由,就得去main.py里注册,很麻烦,而且存在重名问题。
所以我就想,能不能写个函数,每次启动服务时自动导入呢?
基于这个需求,下面的方法就来了
import importlib
import os
# 动态加载路由
def get_routers(folder_name):
path = os.path.join(os.getcwd(), 'app', folder_name)
for folder in os.listdir(path):
if not folder.startswith('__'):
if os.path.isdir(os.path.join(path, folder)): # 若是文件夹
for file in os.listdir(os.path.join(path, folder)):
if not file.startswith('__'):
lib = importlib.import_module(f'app.{folder_name}.{folder}.{file.split(".")[0]}')
sub_router = getattr(lib, 'router')
app.include_router(sub_router)
else: # 若是文件
lib = importlib.import_module(f'app.{folder_name}.{folder.split(".")[0]}')
sub_router = getattr(lib, 'router')
app.include_router(sub_router)
get_routers('routers')
get_routers('internal')
逻辑很简单,就是遍历传入的文件夹,然后找出里面的路由文件,挨个注册,就完事了。
最后修改于2022年7月31日 14:26
©允许规范转载
FastAPI Python版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:https://www.yangyingqi.com/59.html