lavkach3

Форк
0
/
basic_server.py 
109 строк · 3.1 Кб
1
from contextlib import asynccontextmanager
2
from typing import List
3

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
10

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

25

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

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

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

40

41
def init_routers(app_: FastAPI) -> None:
42
    app_.include_router(basic_router)
43

44

45

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

55

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
61
        message = exc.message
62

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

68

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

88

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

92

93
def create_app() -> FastAPI:
94
    app_ = FastAPI(
95
        title="Hide",
96
        description="Hide API",
97
        version="1.0.0",
98
        # docs_url=None if config.ENV == "production" else "/api/basic/docs",
99
        # redoc_url=None if config.ENV == "production" else "/api/basic/dredoc",
100
        dependencies=[Depends(Logging)],
101
        middleware=make_middleware(),
102
    )
103
    init_routers(app_=app_)
104
    init_listeners(app_=app_)
105
    init_cache()
106
    return app_
107

108

109
app = create_app()
110

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

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

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

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