Skip to content

Instantly share code, notes, and snippets.

@Kludex
Created July 9, 2022 14:35
Show Gist options
  • Save Kludex/27fbcc1acad8547c2825fe5035d0b219 to your computer and use it in GitHub Desktop.
Save Kludex/27fbcc1acad8547c2825fe5035d0b219 to your computer and use it in GitHub Desktop.
Dinamically import routers. Do not do this! This is a bad recommendation.
from fastapi import APIRouter
router = APIRouter(prefix="/haha")
@router.get("/haha")
def home():
...
import os
from importlib import import_module
from pathlib import Path
from typing import cast
import uvicorn
from fastapi import APIRouter, FastAPI
app = FastAPI()
ROUTERS_DIR = "routers"
for root, subdirs, files in os.walk(ROUTERS_DIR):
for file in files:
current_file = os.path.join(root, file)
if current_file.endswith(".py"):
module_name = current_file.replace(".py", "").replace("/", ".")
module = import_module(module_name)
for key, value in module.__dict__.items():
if isinstance(value, APIRouter):
router = cast(APIRouter, getattr(module, key))
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app)
from fastapi import APIRouter
router = APIRouter(prefix="/potato")
@router.get("/")
def home():
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment