Example #1
0
def create_app() -> Flask:
    """Create an instance of the app, per the app factory pattern."""
    app = Flask(__name__)

    # Load the app configuration
    app.config.update(config.get_app_config("default.json"))
    app.config.update(
        config.get_app_config(config.get_app_config_file(app.config["ENV"])))

    # Set the app's secret key
    for key in sorted(app.config):
        # Find the secret that ends with "SECRET_KEY" in the name.
        # That's most likely our secret key. If there's more than one
        # key that matches this, this will pick up the first one
        if key.endswith("SECRET_KEY"):
            app.config["SECRET_KEY"] = app.config[key]

            # Now that we've set the key, remove the duplicate key
            del app.config[key]
            break

    # Load the extensions
    init_extensions(app)

    # Register the blueprints
    for bp in all_blueprints:
        import_module(bp.import_name)
        app.register_blueprint(bp)

    # Load any injection/special app handler methods
    with app.app_context():
        import_module("app.middleware")

    return app
Example #2
0
def create_app(mode=os.environ.get('FLASK_MODE', 'app.config.Development')):
    """
    Flask application instantiation with extensions and blueprints
    """
    app = APIFlask(__name__)
    # add configurations
    app_config = config.get(mode)
    app.config.from_object(app_config)
    app_config().init_app(app)

    # initialize all extensions
    init_extensions(app)

    # register blueprints
    # add blueprint registration statements here
    from app.users import users
    app.register_blueprint(users)

    # register error handlers
    app.register_error_handler(400, bad_request)
    app.register_error_handler(Forbidden, forbidden)
    app.register_error_handler(404, not_found)
    app.register_error_handler(405, method_not_supported)
    app.register_error_handler(APIException, conflict)

    return app
Example #3
0
def create_app(config_name: str = "default") -> Flask:
    app = Flask(__name__)
    init_config(app, config_name)

    with app.app_context():
        init_extensions(app)
        init_blueprints(app)
        init_commands(app)

    return app
Example #4
0
def create_app(config_env=app_env):  # factory function
    app = Flask(__name__)

    app.config.from_object(
        f'config.{config_env.capitalize()}Config')  # from route source

    init_extensions(app)

    lang_list = ','.join(app.config['LANGUAGES'])
    lang_prefix = f'<any({lang_list}):lang>'  # tworzenie zmiennej z wartosciami podanymi z listy

    from app.main.views import root
    app.add_url_rule('/', view_func=root)  # add endpoint/function root

    with app.app_context():  # context manager to use app in album form
        from app.album.views import bp_album
        app.register_blueprint(bp_album, url_prefix=f'/{lang_prefix}/album')

    from app.main.views import bp_main
    app.register_blueprint(bp_main, url_prefix=f'/{lang_prefix}/')

    from app.tour.views import bp_tour
    app.register_blueprint(bp_tour, url_prefix=f'/{lang_prefix}/tour')

    from app.auth.views import bp_auth
    app.register_blueprint(bp_auth, url_prefix=f'/{lang_prefix}/auth')

    from app.admin.admin_views import bp_admin
    app.register_blueprint(bp_admin, url_prefix=f'/{lang_prefix}/admin')

    from app.filters import date_format
    app.add_template_filter(date_format)

    # TODO add other common http error codes
    from app.errors import page_not_found
    app.register_error_handler(404, page_not_found)

    from app.url_processors import bp_url_processors
    app.register_blueprint(bp_url_processors)

    app.config['ADMIN_VIEWS'] = [
        re.search('admin.(.*)_table', view).group(1)
        for view in list(app.view_functions.keys())
        if re.search('admin.(.*)_table', view)
    ]
    # print(app.config['ADMIN_VIEWS'])
    # view_functions pobiera wszystkie viewsy podpiete

    Migrate(app, db)

    from cli import register_click_commands
    register_click_commands(app)

    return app
Example #5
0
def create_app(config_name=None):
    # 创建实例
    app = Flask(__name__)
    # 初始化配置
    if config_name not in config:
        config_name = 'default'
    app.config.from_object(config[config_name])
    # 初始化扩展
    init_extensions(app)
    # 注册蓝本
    register_blueprint(app)
    return app
Example #6
0
def create_app(conf='development'):
    app = Flask(__name__)

    # 加载配置
    app.config.from_object(conf_alias[conf])

    # 加载插件
    init_extensions(app)

    # 加载视图函数
    init_views(app)

    return app
Example #7
0
def create_app(config_name):
    app = Flask(__name__,
                static_folder='../static',
                template_folder='../templates')
    app.config['SECRET_KEY'] = 'TYCARRY'
    app.config.from_object(config[config_name])
    init_extensions(app)
    init_func(app)
    config_blueprint(app)
    with app.app_context():
        app.config['MAIL_SUBJECT_PREFIX'] = db_utils.get_option(
            'mail_prefix') or app.config['MAIL_SUBJECT_PREFIX']
        install_init()
    return app
Example #8
0
def create_app(config: Union[str, None] = None, path: str = "config") -> Flask:
    app = Flask(__name__)

    # app.config.from_object(import_module(path).Prod)

    # if config:
    # app.config.dict_config(obj=f"{path}.{config}")

    # logging_config.dictConfig(app.config["LOG_CONF"])   # FROM config file

    init_extensions(app)

    for bluep in blueprints:
        import_module(
            bluep.import_name)  # import the view - 'app.views.corona'
        app.register_blueprint(bluep)

    return app
Example #9
0
def create_app(config: str = None, path: str = "config") -> Flask:
    """Creates a Flask object using the Application Factory pattern.

    Args:
        config: Any config class used to override the default production
            configuration. See config.py for available configurations.
        path: Path to the file that contains the config classes.

    Returns:
        A fully configured and runnable Flask application object.
    """

    # Set the application logger
    configure_logger(config)

    # Create the Flask application object
    app = Flask(__name__)

    # Apply the default (production) configurations
    app.config.from_object(Prod)

    # Override the config if necessary. Otherwise apply the default.
    if config:
        app.config.from_object(obj=f"{path}.{config}")

    # Configure Flask-Login's login manager
    set_user_loader(lm)

    # Initialize all extensions
    init_extensions(app)

    # Set the applications error handlers
    set_error_handlers(app)

    # Import all views and register all Blueprints
    for blueprint in blueprints:
        import_module(blueprint.import_name)
        app.register_blueprint(blueprint)

    return app
Example #10
0
def configure_extensions(app):
    from app.extensions import init_extensions
    init_extensions(app)
Example #11
0
def configure_extensions(app):
    from app.extensions import init_extensions
    init_extensions(app)
Example #12
0
def init_app():
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(Config)

    api = Api(app)
    init_extensions(app)

    app.cli.add_command(cli_commands)

    from app.controllers.ottd import OpenTTDConnection  # noqa
    from app.controllers.company import CompanyTimescaleController  # noqa
    from app.controllers.vehicle import VehicleTimescaleController, VehicleController
    from app.controllers.town import TownController, TownTimescaleController

    def interrupt(signal_received, frame):
        info("Shutting Down...")
        global shutting_down
        ottd_connection.disconnect()
        shutting_down = True
        sleep(2)
        os.kill(os.getpid(), signal.SIGTERM)

    def do_connection_thread():
        sleep(1)
        global connection_thread
        global ottd_connection
        global current_date
        global month_last_update
        global year_last_update
        global shutting_down

        ottd_connection.req_data()
        current_date = ottd_connection.sync_data()()
        if month_last_update != current_date.month:
            # Trigger Vehicle Sync
            info(f" [ New Month {current_date.year}-{current_date.month} ]")
            info(f" [ Requesting Vehicle Updates ] ")
            ottd_connection.refresh_db_vehicles()
            month_last_update = current_date.month
        if year_last_update != current_date.year:
            info(f" [ New Year {current_date.year} ] ")
            info(f" [ Requesting City & Vehicle Updates ] ")
            year_last_update = current_date.year
            # ottd_connection.refresh_db_vehicles()
            # ottd_connection.refresh_db_towns()

        # Set the next thread to happen
        if not shutting_down:
            connection_thread = AppContextThread(target=do_connection_thread)
            connection_thread.start()

    def start_connection_thread(app):
        # Do initialisation stuff here
        global connection_thread
        global ottd_connection
        # Create your thread
        with app.app_context():
            connection_thread = AppContextThread(target=do_connection_thread)
            ottd_connection = OpenTTDConnection()
            # ottd_connection.scan_vehicles(20)
            info(f" [ Start Town Scan ]")
            # ottd_connection.schedule_next_town_scan_batch(947, 10)
            connection_thread.start()

    def start_timescale_thread(app):
        global timescale_updater_thread
        with app.app_context():
            timescale_updater_thread = AppContextThread(
                target=do_timescale_thread
            )
            timescale_updater_thread.start()

    def do_timescale_thread():
        sleep(1)
        global timescale_updater_thread
        global current_date
        global shutting_down
        CompanyTimescaleController.capture_data(current_date)
        VehicleTimescaleController.capture_data(current_date)
        TownTimescaleController.capture_data(current_date)
        if not shutting_down:
            timescale_updater_thread = AppContextThread(
                target=do_timescale_thread
            )
            timescale_updater_thread.start()

    # Only run tasks if flask is being run.
    flask = "flask/__main__.py"

    if Config.WORKER:
        start_connection_thread(app)
        start_timescale_thread(app)
    signal.signal(signal.SIGINT, interrupt)  # ctlr + c

    from app import routes, models

    routes.register_routes(app, api)

    return app