1
from contextlib import asynccontextmanager
4
from fastapi import FastAPI, Request, Depends
5
from fastapi.middleware import Middleware
6
from fastapi.middleware.cors import CORSMiddleware
7
from fastapi.responses import JSONResponse
8
from starlette.requests import HTTPConnection
9
from starlette.types import ASGIApp, Scope, Receive, Send
11
from app.basic.basic_router import basic_router
12
from core.db_config import config
13
from core.env import Env
14
from app.basic import __domain__ as domains
15
from core.exceptions import CustomException
16
from core.fastapi.dependencies import Logging
17
from core.fastapi.middlewares import (
18
AuthenticationMiddleware,
22
from core.helpers.cache import Cache, CustomKeyMaker
23
from core.helpers.cache import RedisBackend
28
Адартер кладется в request для удобства
31
def __init__(self, app: ASGIApp, *args, **kwargs):
34
async def __call__(self, scope: Scope, receive: Receive, send: Send):
35
if scope['type'] in ("http", "websocket"):
36
conn = HTTPConnection(scope)
37
scope['env'] = Env(domains, conn)
38
await self.app(scope, receive, send)
41
def init_routers(app_: FastAPI) -> None:
42
app_.include_router(basic_router)
46
def init_listeners(app_: FastAPI) -> None:
48
@app_.exception_handler(CustomException)
49
async def custom_exception_handler(request: Request, exc: CustomException):
52
content={"error_code": exc.error_code, "message": exc.message},
56
def on_auth_error(request: Request, exc: Exception):
57
status_code, error_code, message = 401, None, str(exc)
58
if isinstance(exc, CustomException):
59
status_code = int(exc.code)
60
error_code = exc.error_code
64
status_code=status_code,
65
content={"error_code": error_code, "message": message},
69
def make_middleware() -> List[Middleware]:
71
Middleware(EnvMidlleWare),
75
allow_credentials=False,
80
AuthenticationMiddleware,
81
backend=AuthBackend(),
82
on_error=on_auth_error,
84
Middleware(SQLAlchemyMiddleware),
89
def init_cache() -> None:
90
Cache.init(backend=RedisBackend(), key_maker=CustomKeyMaker())
93
def create_app() -> FastAPI:
96
description="Hide API",
100
dependencies=[Depends(Logging)],
101
middleware=make_middleware(),
103
init_routers(app_=app_)
104
init_listeners(app_=app_)