-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
42 lines (32 loc) · 1.19 KB
/
main.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
import time
from fastapi import FastAPI
from starlette.requests import Request
from starlette.middleware.cors import CORSMiddleware
from core.config import DEBUG, VERSION, PROJECT_NAME, ALLOWED_HOSTS, API_PREFIX
from api.routers import router as api_router
from db.session import SessionLocal as Session
def get_applications() -> FastAPI:
application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION)
application.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_HOSTS or ["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
application.include_router(api_router, prefix=API_PREFIX)
return application
app = get_applications()
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
request.state.db = Session()
response = await call_next(request)
request.state.db.close()
return response
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response