-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
76 lines (57 loc) · 2.33 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# https://www.serverless.com/plugins/serverless-python-requirements#dealing-with-lambdas-size-limitations
# sourcery skip: use-contextlib-suppress
try:
import unzip_requirements # type: ignore # noqa: F401
except ImportError:
pass
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from mangum import Mangum
from database import init_engine
from exceptions import ChatDemoException
from config import settings
from api.v1 import chat
from utils.logger import logger
def create_app():
logger.info("Initializing FastAPI app")
# Always initialize the database engine
if not settings.SQLALCHEMY_DATABASE_URI:
raise ValueError("SQLALCHEMY_DATABASE_URI must be set")
logger.info(f"Initializing database engine with URI: {settings.SQLALCHEMY_DATABASE_URI}")
init_engine()
logger.info("Database engine initialized")
logger.info("Creating FastAPI app")
app = FastAPI(
root_path=settings.ROOT_PATH if not settings.CUSTOM_DOMAIN else None,
)
logger.info("Adding middleware")
app.add_middleware(
CORSMiddleware, # For handling CORS (https://fastapi.tiangolo.com/tutorial/cors/)
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
max_age=86400, # Bump for browsers that support > 600 seconds like firefox
)
# Handles GZip responses for any request that includes "gzip" in the `Accept-Encoding`` header.
# (https://fastapi.tiangolo.com/advanced/middleware/#gzipmiddleware)
app.add_middleware(GZipMiddleware, minimum_size=1000)
logger.info("Including routers")
app.include_router(chat.router)
@app.get("/", include_in_schema=False)
async def home():
return RedirectResponse("/docs")
@app.get("/status")
async def status():
return {"status": "ok"}
@app.exception_handler(ChatDemoException)
async def app_exception_handler(req, exc: ChatDemoException):
return JSONResponse(status_code=exc.status_code, content=dict(message=exc.message))
return app
app = create_app()
handler = Mangum(app, lifespan="off")
def lambda_handler(event, context):
logger.info("Lambda handler called")
return handler(event, context)