forked from teamhide/fastapi-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
90 lines (73 loc) · 2.45 KB
/
server.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from typing import List
from fastapi import FastAPI, Request, Depends
from fastapi.middleware import Middleware
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api import router
from api.home.home import home_router
from core.config import config
from core.exceptions import CustomException
from core.fastapi.dependencies import Logging
from core.fastapi.middlewares import (
AuthenticationMiddleware,
AuthBackend,
SQLAlchemyMiddleware,
ResponseLogMiddleware,
)
from core.helpers.cache import Cache, RedisBackend, CustomKeyMaker
def init_routers(app_: FastAPI) -> None:
app_.include_router(home_router)
app_.include_router(router)
def init_listeners(app_: FastAPI) -> None:
# Exception handler
@app_.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
return JSONResponse(
status_code=exc.code,
content={"error_code": exc.error_code, "message": exc.message},
)
def on_auth_error(request: Request, exc: Exception):
status_code, error_code, message = 401, None, str(exc)
if isinstance(exc, CustomException):
status_code = int(exc.code)
error_code = exc.error_code
message = exc.message
return JSONResponse(
status_code=status_code,
content={"error_code": error_code, "message": message},
)
def make_middleware() -> List[Middleware]:
middleware = [
Middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
),
Middleware(
AuthenticationMiddleware,
backend=AuthBackend(),
on_error=on_auth_error,
),
Middleware(SQLAlchemyMiddleware),
Middleware(ResponseLogMiddleware),
]
return middleware
def init_cache() -> None:
Cache.init(backend=RedisBackend(), key_maker=CustomKeyMaker())
def create_app() -> FastAPI:
app_ = FastAPI(
title="Hide",
description="Hide API",
version="1.0.0",
docs_url=None if config.ENV == "production" else "/docs",
redoc_url=None if config.ENV == "production" else "/redoc",
dependencies=[Depends(Logging)],
middleware=make_middleware(),
)
init_routers(app_=app_)
init_listeners(app_=app_)
init_cache()
return app_
app = create_app()