ScanOS/backend/app/main.py

55 lines
1.3 KiB
Python
Raw Normal View History

2024-07-07 00:30:13 +02:00
import threading, logging
2023-09-21 14:56:01 +02:00
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import FastAPI, Depends
from app.data import models
from app.data.database import SessionLocal, engine
2024-07-07 00:30:13 +02:00
from uvicorn.logging import DefaultFormatter
2023-09-21 14:56:01 +02:00
from app.scanner.scanner import Scanner
from app.scanner.scanner import Status as ScannerStatus
2024-07-07 00:30:13 +02:00
# Set up logging
logger = logging.getLogger()
__syslog = logging.StreamHandler()
__syslog.setFormatter(DefaultFormatter(fmt="%(levelprefix)s %(message)s", use_colors=True))
logger.setLevel(logging.INFO)
logger.addHandler(__syslog)
# Create database
2023-09-21 14:56:01 +02:00
models.Base.metadata.create_all(bind=engine)
2024-07-07 00:30:13 +02:00
# Set up scanner instance
__scanner = Scanner("/var/www/html/img", logger)
2023-09-21 14:56:01 +02:00
2024-07-07 00:30:13 +02:00
# Preload scanner after FastAPI start
2023-09-21 14:56:01 +02:00
@asynccontextmanager
async def __lifespan(app: FastAPI):
threading.Thread(target=__scanner.preload).start()
yield
app = FastAPI(lifespan=__lifespan)
# SQLAlchemiy session dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_scanner():
return __scanner
from app.routers import power
app.include_router(power.router)
from app.routers import scan
app.include_router(scan.router)
@app.get("/api/ready")
async def __ready(scanner: Annotated[Scanner, Depends(get_scanner)]):
return scanner.get_status() != ScannerStatus.INITIALIZED