1
|
|
|
from flask import Flask |
2
|
|
|
from werkzeug.exceptions import HTTPException |
3
|
|
|
|
4
|
|
|
from app import extensions |
5
|
|
|
from app.blueprints import api_v1_blueprint |
6
|
|
|
from app.hooks.error import broad_exception_error_handler, http_exception_handler |
7
|
|
|
from app.hooks.request_context import after_request |
8
|
|
|
|
9
|
|
|
# -- API load |
10
|
|
|
from app.views import sample |
11
|
|
|
# -- |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
def register_extensions(app): |
15
|
|
|
extensions.swagger.template = app.config['SWAGGER_TEMPLATE'] |
16
|
|
|
|
17
|
|
|
extensions.cors.init_app(app) |
18
|
|
|
extensions.jwt.init_app(app) |
19
|
|
|
extensions.mongoengine.init_app(app) |
20
|
|
|
extensions.validator.init_app(app) |
21
|
|
|
extensions.swagger.init_app(app) |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
def register_blueprints(app): |
25
|
|
|
handle_exception_func = app.handle_exception |
26
|
|
|
handle_user_exception_func = app.handle_user_exception |
27
|
|
|
# register_blueprint 시 defer되었던 함수들이 호출되며, flask-restful.Api._init_app()이 호출되는데 |
28
|
|
|
# 해당 메소드가 app 객체의 에러 핸들러를 오버라이딩해서, 별도로 적용한 handler의 HTTPException 관련 로직이 동작하지 않음 |
29
|
|
|
# 따라서 두 함수를 임시 저장해 두고, register_blueprint 이후 함수를 재할당하도록 함 |
30
|
|
|
|
31
|
|
|
app.register_blueprint(api_v1_blueprint) |
32
|
|
|
|
33
|
|
|
app.handle_exception = handle_exception_func |
34
|
|
|
app.handle_user_exception = handle_user_exception_func |
35
|
|
|
|
36
|
|
|
|
37
|
|
|
def register_hooks(app): |
38
|
|
|
app.after_request(after_request) |
39
|
|
|
app.register_error_handler(HTTPException, http_exception_handler) |
40
|
|
|
app.register_error_handler(Exception, broad_exception_error_handler) |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
def create_app(*config_cls) -> Flask: |
44
|
|
|
print('[INFO] Flask application initialized with {}'.format(', '.join([config.__name__ for config in config_cls]))) |
45
|
|
|
|
46
|
|
|
app = Flask(__name__) |
47
|
|
|
|
48
|
|
|
for config in config_cls: |
49
|
|
|
app.config.from_object(config) |
50
|
|
|
|
51
|
|
|
register_extensions(app) |
52
|
|
|
register_blueprints(app) |
53
|
|
|
register_hooks(app) |
54
|
|
|
|
55
|
|
|
return app |
56
|
|
|
|