welcometoFightclub's picture
Upload 48 files
a263bf4 verified
Raw History Blame Contribute Delete
1.84 kB
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from app.api.routes import documents, jobs
from app.core.exceptions import ApplicationError
from app.database import engine
from app.models.base import Base
STATIC_DIRECTORY = Path(__file__).parent / "static"
DOCUMENTATION_DIRECTORY = Path(__file__).parents[2] / "docs"
@asynccontextmanager
async def lifespan(_: FastAPI):
# Suitable for the first SQLite implementation. Use Alembic migrations before production.
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
yield
await engine.dispose()
app = FastAPI(title="Purchase order extractor", version="0.1.0", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=STATIC_DIRECTORY), name="static")
app.mount("/project-docs", StaticFiles(directory=DOCUMENTATION_DIRECTORY, html=True), name="project-docs")
app.include_router(documents.router)
app.include_router(jobs.router)
@app.exception_handler(ApplicationError)
async def application_error_handler(_: Request, exc: ApplicationError) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": exc.code, "message": exc.message}},
)
@app.get("/", include_in_schema=False)
async def home() -> FileResponse:
return FileResponse(STATIC_DIRECTORY / "index.html")
@app.get("/health")
async def health() -> dict[str, str]:
async with engine.connect() as connection:
await connection.execute(text("SELECT 1"))
return {"status": "ok"}
def run() -> None:
import uvicorn
uvicorn.run("app.main:app", host="127.0.0.1", port=8000, reload=True)