Created
July 9, 2022 14:35
-
-
Save Kludex/27fbcc1acad8547c2825fe5035d0b219 to your computer and use it in GitHub Desktop.
Dinamically import routers. Do not do this! This is a bad recommendation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import APIRouter | |
router = APIRouter(prefix="/haha") | |
@router.get("/haha") | |
def home(): | |
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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