Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.7 kB
2
Indexable
Never
import logging

from fastapi import Depends, FastAPI
from sqlalchemy import text
from sqlalchemy.orm import Session
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
from property_rater.valuations_tool import models

from property_rater.api_versions.api_v1.api import api_router_v1
from property_rater.config import get_app_settings
from property_rater.database.session import get_database_session, get_engine

logger = logging.getLogger(__name__)

description = """
A Property Rater Service built on FastAPI. 
Served on Azure Functions: https://github.com/Azure-Samples/fastapi-on-azure-functions/
"""


app = FastAPI(
    title="Property Rater Service",
    description=description,
    default_response_class=JSONResponse,
    openapi_url=f"/api/v1/openapi.json",
    version="1"
)

models.Base.metadata.create_all(bind=get_engine())  # I'd propose wrapping this in a function,
#                                                     # so it can be only called in a controlled manner.


@app.on_event("startup")
async def startup(session: Session = Depends(get_database_session)) -> None:
    logger.info("Starting service.")
    session.execute(text("SELECT 1"))
    logger.info("Service initialization completed.")


@app.on_event("shutdown")
async def shutdown(session: Session = Depends(get_database_session)) -> None:
    logger.info("Shutting down service.")
    session.close_all()
    logger.info("Service shutdown completed.")


app.add_middleware(
    CORSMiddleware,
    allow_origins=[str(origin) for origin in get_app_settings().BACKEND_CORS_ORIGINS],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


app.include_router(api_router_v1, prefix="/api/v1")