lavkach3

Форк
0
/
inventory_server.py 
107 строк · 3.1 Кб
1
from typing import List
2

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
9

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,
18
    AuthBackend,
19
    SQLAlchemyMiddleware,
20
)
21
from core.helpers.cache import Cache, CustomKeyMaker
22
from core.helpers.cache import RedisBackend
23

24

25
class EnvMidlleWare:
26
    """
27
    Адартер кладется в request для удобства
28
    """
29

30
    def __init__(self, app: ASGIApp, *args, **kwargs):
31
        self.app = app
32

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)
38

39

40
def init_routers(app_: FastAPI) -> None:
41
    app_.include_router(inventory_router)
42

43

44
def init_listeners(app_: FastAPI) -> None:
45
    # Exception handler
46
    @app_.exception_handler(CustomException)
47
    async def custom_exception_handler(request: Request, exc: CustomException):
48
        return JSONResponse(
49
            status_code=exc.code,
50
            content={"error_code": exc.error_code, "message": exc.message},
51
        )
52

53

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
59
        message = exc.message
60

61
    return JSONResponse(
62
        status_code=status_code,
63
        content={"error_code": error_code, "message": message},
64
    )
65

66

67
def make_middleware() -> List[Middleware]:
68
    middleware = [
69
        Middleware(EnvMidlleWare),
70
        Middleware(
71
            CORSMiddleware,
72
            allow_origins=["*"],
73
            allow_credentials=False,
74
            allow_methods=["*"],
75
            allow_headers=["*"],
76
        ),
77
        Middleware(
78
            AuthenticationMiddleware,
79
            backend=AuthBackend(),
80
            on_error=on_auth_error,
81
        ),
82
        Middleware(SQLAlchemyMiddleware),
83
    ]
84
    return middleware
85

86

87
def init_cache() -> None:
88
    Cache.init(backend=RedisBackend(), key_maker=CustomKeyMaker())
89

90

91
def create_app() -> FastAPI:
92
    app_ = FastAPI(
93
        title="Hide",
94
        description="Hide API",
95
        version="1.0.0",
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(),
100
    )
101
    init_routers(app_=app_)
102
    init_listeners(app_=app_)
103
    init_cache()
104
    return app_
105

106

107
app = create_app()
108

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.