Skip to content

Commit 5a900d8

Browse files
committed
Add dynamic router scanning
Eliminates the need to import and include API routers one by one in the main file.
1 parent 72288c1 commit 5a900d8

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

app/main.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,21 @@
1-
from fastapi import FastAPI
1+
import importlib
2+
import pkgutil
3+
4+
from fastapi import APIRouter, FastAPI
25
from fastapi.middleware.cors import CORSMiddleware
36

47
from app import lifespan_func
58

6-
from .routers import course, scraper
9+
10+
def scan_and_include_routers(app: FastAPI, package: str) -> None:
11+
package_module = importlib.import_module(package)
12+
for _, module_name, _ in pkgutil.iter_modules(package_module.__path__):
13+
module = importlib.import_module(f"{package}.{module_name}")
14+
for attr_name in dir(module):
15+
attr = getattr(module, attr_name)
16+
if isinstance(attr, APIRouter):
17+
app.include_router(attr)
18+
719

820
app = FastAPI(root_path="/api/v1", lifespan=lifespan_func)
921
app.add_middleware(
@@ -12,5 +24,5 @@
1224
allow_methods=["GET", "POST"],
1325
allow_headers=["*"],
1426
)
15-
app.include_router(course.router)
16-
app.include_router(scraper.router)
27+
_package_name = __name__.split(".")[0]
28+
scan_and_include_routers(app, f"{_package_name}.routers")

0 commit comments

Comments
 (0)