karl/app/main.py
2025-10-06 23:45:30 +02:00

55 lines
1.7 KiB
Python

import os
import yaml
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader, select_autoescape
from app.api.v1 import router as api_v1_router
# Inicjalizacja Jinja2
templates_env = Environment(
loader=FileSystemLoader("app/templates"),
autoescape=select_autoescape(["html", "xml"]),
)
def load_config() -> dict:
"""
Ładuje konfigurację z pliku YAML.
Domyślna ścieżka: config/config.yaml
Można nadpisać przez APP_CONFIG_FILE.
"""
config_path = os.getenv("APP_CONFIG_FILE", "config/config.yaml")
if not os.path.exists(config_path):
# Zwróć minimalną domyślną konfigurację, jeśli plik nie istnieje
return {
"app": {"host": "127.0.0.1", "port": 8000, "reload": True},
}
with open(config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
app = FastAPI(title="Karl", version="0.1.0")
# Załaduj konfigurację do stanu aplikacji
app.state.config = load_config()
# Rejestracja routera API pod /api/v1
app.include_router(api_v1_router, prefix="/api/v1", tags=["v1"])
# Przykładowy endpoint HTML
@app.get("/", response_class=HTMLResponse)
async def index(request: Request) -> HTMLResponse:
template = templates_env.get_template("index.html")
html = template.render(title="Strona główna", request=request)
return HTMLResponse(content=html)
def run() -> None:
import uvicorn
cfg = getattr(app.state, "config", {})
host = cfg.get("app", {}).get("host", "127.0.0.1")
port = int(cfg.get("app", {}).get("port", 8000))
reload = bool(cfg.get("app", {}).get("reload", True))
uvicorn.run("app.main:app", host=host, port=port, reload=reload)