-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
58 lines (41 loc) · 1.68 KB
/
Copy pathapp.py
File metadata and controls
58 lines (41 loc) · 1.68 KB
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
from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError, ResponseValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.authentication import AuthenticationMiddleware
from util.logger import init_logger
init_logger()
def register_router(_app: FastAPI):
from core import api_router, page_router
_app.include_router(page_router.router)
_app.include_router(api_router.router, prefix="/api")
def add_custom_exception_handlers(_app: FastAPI):
from util.exception_util import request_validation_exception_handler, response_validation_exception_handler
_app.add_exception_handler(RequestValidationError, request_validation_exception_handler)
_app.add_exception_handler(ResponseValidationError, response_validation_exception_handler)
def register_middlewares(_app: FastAPI):
_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def create_app(span) -> FastAPI:
_app = FastAPI(lifespan=span)
register_router(_app)
register_middlewares(_app)
add_custom_exception_handlers(_app)
return _app
@asynccontextmanager
async def lifespan(application: FastAPI): # noqa
from base.connector import database_connector
"""
Use context manager to manage the lifespan of the application instead of using the startup and shutdown events.
"""
yield
await database_connector.engine.dispose()
app = create_app(lifespan)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=5555, reload=True, workers=8)