3
from fastapi import FastAPI, Request, Depends
4
from fastapi.middleware import Middleware
5
from fastapi.middleware.cors import CORSMiddleware
6
from fastapi.responses import JSONResponse
7
from starlette.requests import HTTPConnection
8
from starlette.types import ASGIApp, Scope, Receive, Send
10
from app.inventory.inventory_router import inventory_router
11
from core.db_config import config
12
from core.env import Env
13
from app.inventory import __domain__ as inventory_domain
14
from core.exceptions import CustomException
15
from core.fastapi.dependencies import Logging
16
from core.fastapi.middlewares import (
17
AuthenticationMiddleware,
21
from core.helpers.cache import Cache, CustomKeyMaker
22
from core.helpers.cache import RedisBackend
27
Адартер кладется в request для удобства
30
def __init__(self, app: ASGIApp, *args, **kwargs):
33
async def __call__(self, scope: Scope, receive: Receive, send: Send):
34
if scope['type'] in ("http", "websocket"):
35
conn = HTTPConnection(scope)
36
scope['env'] = Env([inventory_domain], conn)
37
await self.app(scope, receive, send)
40
def init_routers(app_: FastAPI) -> None:
41
app_.include_router(inventory_router)
44
def init_listeners(app_: FastAPI) -> None:
46
@app_.exception_handler(CustomException)
47
async def custom_exception_handler(request: Request, exc: CustomException):
50
content={"error_code": exc.error_code, "message": exc.message},
54
def on_auth_error(request: Request, exc: Exception):
55
status_code, error_code, message = 401, None, str(exc)
56
if isinstance(exc, CustomException):
57
status_code = int(exc.code)
58
error_code = exc.error_code
62
status_code=status_code,
63
content={"error_code": error_code, "message": message},
67
def make_middleware() -> List[Middleware]:
69
Middleware(EnvMidlleWare),
73
allow_credentials=False,
78
AuthenticationMiddleware,
79
backend=AuthBackend(),
80
on_error=on_auth_error,
82
Middleware(SQLAlchemyMiddleware),
87
def init_cache() -> None:
88
Cache.init(backend=RedisBackend(), key_maker=CustomKeyMaker())
91
def create_app() -> FastAPI:
94
description="Hide API",
96
docs_url=None if config.ENV == "production" else "/api/inventory/docs",
97
redoc_url=None if config.ENV == "production" else "/api/inventory/redoc",
98
dependencies=[Depends(Logging)],
99
middleware=make_middleware(),
101
init_routers(app_=app_)
102
init_listeners(app_=app_)