fastapi 自动加载路由

引言

每次添加一个接口的py,都要配置一下main.py,很麻烦,所以遍历目录,自动加就好了

关键代码

base_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "routers")

def append_router(router_path):
    try:
        router_path_list = os.listdir(router_path)
        for route in router_path_list:
            if route == "__init__.py":
                continue
            if route.endswith(".py"):
                try:
                    sub_dir = (
                        router_path.replace(base_dir, "")
                        .replace("\\", ".")
                        .replace("/", ".")
                    )
                    exec(f"from routers{sub_dir} import {route[:-3]}")
                    eval(f"app.include_router({route[:-3]}.router)")
                except Exception as e:
                    import traceback
                    traceback.print_exc()
            if os.path.isdir(os.path.join(router_path, route)):
                append_router(os.path.join(router_path, route))
    except Exception as e:
        print(2, e)


append_router(base_dir)

结语

这只是一个建设性的功能代码,实际使用需要进一步的优化。哎,这周忙坏了,水一篇吧。

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。