lavkach3

Форк
0
/
prescription_server.py 
124 строки · 3.5 Кб
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.prescription.prescription_router import router
12
from core.db_config import config
13
from core.env import Env
14
from app.prescription 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.broker.tkq import broker
23
from core.helpers.cache import Cache, CustomKeyMaker
24
from core.helpers.cache import RedisBackend
25

26

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

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

35
    async def __call__(self, scope: Scope, receive: Receive, send: Send):
36
        if scope['type'] in  ("http", "websocket"):
37
            conn = HTTPConnection(scope)
38
            scope['env'] = Env(domains, conn)
39
        await self.app(scope, receive, send)
40

41

42
def init_routers(app_: FastAPI) -> None:
43
    app_.include_router(router)
44

45

46

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

56

57
def on_auth_error(request: Request, exc: Exception):
58
    status_code, error_code, message = 401, None, str(exc)
59
    if isinstance(exc, CustomException):
60
        status_code = int(exc.code)
61
        error_code = exc.error_code
62
        message = exc.message
63

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

69

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

89

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

93
@asynccontextmanager
94
async def lifespan(app: FastAPI):
95
    """
96
        Старт сервера
97
    """
98
    if not broker.is_worker_process:
99
        await broker.startup()
100
    yield
101
    """
102
            Выключение сервера
103
    """
104
    if not broker.is_worker_process:
105
        await broker.shutdown()
106

107
def create_app() -> FastAPI:
108
    app_ = FastAPI(
109
        title="Hide",
110
        lifespan=lifespan,
111
        description="Hide API",
112
        version="1.0.0",
113
        # docs_url=None if config.ENV == "production" else "/api/prescription/docs",
114
        # redoc_url=None if config.ENV == "production" else "/api/prescription/dredoc",
115
        dependencies=[Depends(Logging)],
116
        middleware=make_middleware(),
117
    )
118
    init_routers(app_=app_)
119
    init_listeners(app_=app_)
120
    init_cache()
121
    return app_
122

123

124
app = create_app()
125

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

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

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

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