1+ from cmath import log
2+ import os
3+
4+ from flask import Flask
5+ from flask_sqlalchemy import SQLAlchemy
6+ from flask_socketio import SocketIO
7+ from celery import Celery
8+
9+ from .config import flask_config
10+
11+ # Flask extensions
12+ db = SQLAlchemy ()
13+ socketio = SocketIO (cors_allowed_origins = "*" , engineio_logger = True )
14+ celery = Celery (__name__ ,
15+ broker = os .environ .get ('CELERY_BROKER_URL' , 'redis://' ),
16+ backend = os .environ .get ('CELERY_BROKER_URL' , 'redis://' ))
17+ celery .config_from_object ('api.celery_config' )
18+
19+ # Import models so that they are registered with SQLAlchemy
20+ from . import models # noqa
21+
22+ # Import celery task so that it is registered with the Celery workers
23+ from .tasks import run_flask_request # noqa
24+
25+ # Import Socket.IO events so that they are registered with Flask-SocketIO
26+ from . import events # noqa
27+
28+
29+ def create_app (config_name = None , main = True ):
30+ if config_name is None :
31+ config_name = os .environ .get ('FLASK_ENV' , 'development' )
32+ app = Flask (__name__ , static_folder = '../build' , static_url_path = '/' )
33+ app .config .from_object (flask_config [config_name ])
34+
35+ # Initialize flask extensions
36+ db .init_app (app )
37+
38+ @app .cli .command ('createdb' )
39+ def createdb ():
40+ db .create_all ()
41+
42+ if main :
43+ # Initialize socketio server and attach it to the message queue, so
44+ # that everything works even when there are multiple servers or
45+ # additional processes such as Celery workers wanting to access
46+ # Socket.IO
47+ socketio .init_app (app ,
48+ message_queue = app .config ['SOCKETIO_MESSAGE_QUEUE' ])
49+ else :
50+ # Initialize socketio to emit events through through the message queue
51+ # Note that since Celery does not use eventlet, we have to be explicit
52+ # in setting the async mode to not use it.
53+ socketio .init_app (None ,
54+ message_queue = app .config ['SOCKETIO_MESSAGE_QUEUE' ],
55+ async_mode = 'threading' )
56+ celery .conf .update (flask_config [config_name ].CELERY_CONFIG )
57+
58+ # Register web application routes
59+ from .main import main as main_blueprint
60+ app .register_blueprint (main_blueprint )
61+
62+ # Register API routes
63+ from .blueprints import api as api_blueprint
64+ app .register_blueprint (api_blueprint , url_prefix = '/api' )
65+
66+ # Register async tasks support
67+ from .tasks import tasks_bp as tasks_blueprint
68+ app .register_blueprint (tasks_blueprint , url_prefix = '/tasks' )
69+
70+ return app
0 commit comments