-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.py
85 lines (73 loc) · 3.32 KB
/
App.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import logging
import sys
from fastapi.middleware.cors import CORSMiddleware
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from fastapi_sqlalchemy import DBSessionMiddleware
from src.configuration.Configuration import Configuration
from src.versions.v1 import router as v1_router
class App:
def __init__(self, app):
self.app = app
def setup_routers(self):
self.app.include_router(v1_router)
"""
Simplify operation IDs so that generated API clients have simpler function
names.
Should be called only after all routes have been added.
"""
for route in self.app.routes:
if isinstance(route, APIRoute):
route.operation_id = route.tags[-1].replace(
' ', '').lower() if len(route.tags) > 0 else ''
route.operation_id += '_' + route.name
# print(route.operation_id)
def setup_middleware(self):
self.app.add_middleware(DBSessionMiddleware,
db_url=Configuration.database.url)
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
def setup_exceptions(self):
from src.error import error_handler as eh
from src.error.AuthenticationException import AuthenticationException
from src.error.InputException import InputException
from src.error.InvalidDataException import InvalidDataException
from src.error.NotFoundException import NotFoundException
from src.error.ValidationException import ValidationException
from src.error.MailClientException import MailClientException
self.app.add_exception_handler(AuthenticationException,
eh.authentication_exception_handler)
self.app.add_exception_handler(NotFoundException,
eh.not_found_exception_handler)
self.app.add_exception_handler(ValidationException,
eh.validation_exception_handler)
self.app.add_exception_handler(InvalidDataException,
eh.invalid_data_exception_handler)
self.app.add_exception_handler(InputException,
eh.input_exception_handler)
self.app.add_exception_handler(MailClientException,
eh.initialize_exception_handler)
def setup_static_folder(self):
self.app.mount('/static',
StaticFiles(directory='static'),
name='static')
def setup_logger(self, logger):
logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler(sys.stdout)
log_formatter = logging.Formatter(
"%(asctime)s [%(processName)s: %(process)d] [%(threadName)s: %(thread)d] [%(levelname)s] %(name)s: %(message)s"
)
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)
def setup_all(self, logger):
self.setup_static_folder()
self.setup_middleware()
self.setup_logger(logger)
self.setup_exceptions()
self.setup_routers()