File tree Expand file tree Collapse file tree 1 file changed +16
-4
lines changed
Expand file tree Collapse file tree 1 file changed +16
-4
lines changed Original file line number Diff line number Diff line change 1- from fastapi import FastAPI
1+ import importlib
2+ import pkgutil
3+
4+ from fastapi import APIRouter , FastAPI
25from fastapi .middleware .cors import CORSMiddleware
36
47from 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
820app = FastAPI (root_path = "/api/v1" , lifespan = lifespan_func )
921app .add_middleware (
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" )
You can’t perform that action at this time.
0 commit comments