def create_app(config_environment): app = Flask('FlaskProject') config_object = environments[config_environment]() config_object.init_app(app) db.init_app(app) # Initialize flask-alembic alembic = Alembic() alembic.init_app(app) # Mount blueprints app.register_blueprint(bpp) # Log starting of application instance app.logger.info("Starting Flask '{0}' in '{1}' mode".format( app.name, config_environment)) jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('/FlaskProject/templates'), ]) _initialize_global_exception_handler(app) return app
def _set_flask_alembic(): from flask_alembic import Alembic """ Add the SQLAlchemy object in the global extension """ application.app.extensions["sqlalchemy"] = type('', (), {"db": db}) alembic = Alembic() alembic.init_app(application.app) return alembic
def create_app(extra_app_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY=DEV_SECRET_KEY, SQLALCHEMY_DATABASE_URI= f'sqlite:///{(Path(app.instance_path) / "yap.sqlite").absolute().as_posix()}', SQLALCHEMY_TRACK_MODIFICATIONS=False, ALEMBIC_CONTEXT={"render_as_batch": True}, YAP_EXPIRE_IN=DEFAULT_YAP_EXPIRE_IN, YAP_PASTE_RATE_LIMIT=datetime.timedelta(seconds=30), YAP_NUM_REVERSE_PROXIES=0, ) app.config.from_pyfile("config.py", silent=True) if extra_app_config: app.config.from_mapping(extra_app_config) if app.config["SECRET_KEY"] == DEV_SECRET_KEY and not (app.debug or app.testing): raise RuntimeError("Please set SECRET_KEY") with contextlib.suppress(OSError): os.makedirs(app.instance_path) db.init_app(app) alembic = Alembic() alembic.init_app(app) from yap import paste app.register_blueprint(paste.bp) return app
def run_migrations(app: Flask): """Run the database migrations.""" with app.app_context(): app.logger.info('Running Alembic Migrations') alembic = Alembic() alembic.init_app(app, run_mkdir=False) alembic.upgrade('head')
def app_factory(script_info): config_path = getattr(script_info, 'config', None) instance_path = getattr(script_info, 'instance_path', None) click.echo(f"Config Path: {config_path} Instance Path: {instance_path}") app = make_app(config_path=config_path, instance_path=instance_path) Alembic(app=app) return app
def app(): """ Deprecated: do not use this fixture for new tests, unless for very specific use cases. Use `isolated_app` instead. Flask application with demosite data and without any database isolation: any db transaction performed during the tests are persisted into the db. Creates a Flask application with a simple testing configuration, then creates an application context and inside of it recreates all databases and indices from the fixtures. Finally it yields, so that all tests that explicitly use the ``app`` fixture have access to an application context. See: http://flask.pocoo.org/docs/0.12/appcontext/. """ app = create_app( DEBUG=False, # Tests may fail when turned on because of Flask bug (A setup function was called after the first request was handled. when initializing - when Alembic initialization) WTF_CSRF_ENABLED=False, CELERY_TASK_ALWAYS_EAGER=True, CELERY_RESULT_BACKEND='cache', CELERY_CACHE_BACKEND='memory', CELERY_TASK_EAGER_PROPAGATES=True, SECRET_KEY='secret!', RECORD_EDITOR_FILE_UPLOAD_FOLDER='tests/integration/editor/temp', TESTING=True, ) with app.app_context(): # Celery task imports must be local, otherwise their # configuration would use the default pickle serializer. from inspirehep.modules.migrator.tasks import add_citation_counts from inspirehep.modules.migrator.tasks import migrate_from_file db.session.close() db.drop_all() drop_alembic_version_table() alembic = Alembic(app=current_app) alembic.upgrade() _es = app.extensions['invenio-search'] list(_es.delete(ignore=[404])) list(_es.create(ignore=[400])) init_all_storage_paths() init_users_and_permissions() migrate_from_file('./inspirehep/demosite/data/demo-records.xml.gz', wait_for_results=True) es.indices.refresh( 'records-hep') # Makes sure that all HEP records were migrated. add_citation_counts() es.indices.refresh( 'records-hep') # Makes sure that all citation counts were added. yield app
def init_db(app): """Initialize SQLAlchemy""" from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic db = SQLAlchemy(app) Alembic(app) return db
def create_app(): app = Flask(__name__) app.config.from_object('{{ cookiecutter.package_name}}.config.settings') db.init_app(app) api_v1.init_app(app) Alembic(app) return app
def create_all(app): alembic = Alembic(app=app) alembic.upgrade() _es = app.extensions['invenio-search'] list(_es.create(ignore=[400])) init_all_storage_paths() init_users_and_permissions()
def create_app(): app = Flask(__name__) app.config.from_object('star_wars.config.settings') db.init_app(app) api_v1.init_app(app) Alembic(app) return app
def create_app(): app = Flask(__name__) app.config.from_object('api_storage_content.config.settings') db.init_app(app) api_v1.init_app(app) Alembic(app) return app
def manage(): """ Run 'migrate' followed by 'upgrade' :return: """ migrate = Migrate(app, db) manager = Manager(app) alembic = Alembic(app) manager.add_command('db', alembic_manager) manager.run()
def init_db(): LOGGER.info('Recreating the DB') db.session.close() db.drop_all() drop_alembic_version_table() alembic = Alembic(app=current_app) alembic.upgrade() db.session.commit() LOGGER.info('Recreating the DB: done') return jsonify("Db recreated")
def __init__(self, app=None, **kwargs): """Initialize the database management extension. Args: app: Flask application kwargs: Optional arguments to Flask-SQLAlchemy. """ self.triggers = dict() self.scripts = dict() self.alembic = Alembic(run_mkdir=False, command_name='alembic') if app: self.init_app(app, **kwargs)
def create_app(config_environment): app = Flask('videostore') config_object = environments[config_environment]() config_object.init_app(app) db.init_app(app) # Initialize flask-alembic alembic = Alembic() alembic.init_app(app) return app
def clear_environment(app): with app.app_context(): db.session.close() db.drop_all() drop_alembic_version_table() alembic = Alembic(app=app) alembic.upgrade() list(current_search.delete(ignore=[404])) list(current_search.create(ignore=[400])) current_search.flush_and_refresh('records-hep') init_all_storage_paths() init_users_and_permissions()
def clear_environment(app): with app.app_context(): db.session.close() db.drop_all() drop_alembic_version_table() alembic = Alembic(app=app) alembic.upgrade() _es = app.extensions['invenio-search'] list(_es.delete(ignore=[404])) list(_es.create(ignore=[400])) es.indices.refresh('records-hep') init_all_storage_paths() init_users_and_permissions()
def create_app(app_name, config_obj, with_api=True): """ Generates and configures the main shop application. All additional """ # Launching application app = Flask(app_name) # So the engine would recognize the root package # Load Configuration app.config.from_object(config_obj) # Initializing Database db = SQLAlchemy(app) app.db = db # migrate = Migrate(app, db) app.cache = Cache(app) # Initializing Alembic alembic = Alembic() alembic.init_app(app) app.alembic = alembic moment = Moment(app) app.moment = moment # Initializing the restful API if with_api: api = Api(app, prefix='/rest') app.api = api # Initialize Logging if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler( "/var/log/locales/%s.log" % app.config.get("LOGFILE_NAME", app_name), maxBytes=500 * 1024) file_handler.setLevel(logging.INFO) from logging import Formatter file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) app.logger.addHandler(file_handler) # include an api_registry to the application app.api_registry = [] # a simple list holding the values to be registered return app
def setup_app(): db.init_app(application) CORS(application) Swagger(application) Migrate(application, db) Alembic(application) api = Api(application, prefix="/api/v1") api.add_resource(CreditCardResource, "/credit-card/", methods=['POST']) api.add_resource(BoletoResource, "/boleto/", methods=['POST']) api.add_resource(PaymentResource, "/payment/", methods=['GET']) api.add_resource(PaymentoDetailsResource, "/payment/<int:id>", methods=['GET']) return application
def create_app(app_name, config_obj, api_prefix='/api/v1'): """ Generates and configures the main application.""" # Launching application app = Flask(app_name) # So the engine would recognize the root package with app.app_context(): # Load Configuration app.config.from_object(config_obj) # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt # Initializing Database db = SQLAlchemy(app) app.db = db # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', '.login') login_manager.session_protection = 'strong' login_manager.init_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing Alembic alembic = Alembic() alembic.init_app(app) app.alembic = alembic api = Api(app, prefix=api_prefix) app.api = api # include an api_registry to the application app.api_registry = [ ] # a simple list holding the values to be registered return app
def create_app(): app = Flask(__name__) app.config.from_object('resume_api.config.settings') db.init_app(app) api_v1.init_app(app) api_v1_w_auth.init_app(app) Alembic(app) CORS(app) # if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port) return app
def init_tenant(tenant, db): query = exists( select([text("schema_name") ]).select_from(text("information_schema.schemata")).where( text("schema_name = '%s'" % tenant))) tenant_exists = db.session.query(query).scalar() if not tenant_exists: create_tenant(tenant, db) switch_tenant(tenant, db) # Makes sure alembic install its meta information tables into the db (schema/namespace) with app.app_context(): g.tenant = tenant alembic = Alembic() alembic.init_app(app, run_mkdir=False) alembic.upgrade() install_triggers(db, tenant) else: switch_tenant(tenant, db)
def create_app(config_environment): app = Flask('videostore') config_object = environments[config_environment]() config_object.init_app(app) db.init_app(app) # Initialize flask-alembic alembic = Alembic() alembic.init_app(app) # Mount blueprints app.register_blueprint(api, url_prefix='/api') # Log starting of application instance app.logger.info("Starting Flask '{0}' in '{1}' mode".format( app.name, config_environment)) _initialize_global_exception_handler(app) return app
def app(request): """Flask application fixtures. Creates a Flask application with a simple testing configuration, then creates an application context and inside of it recreates all databases and indices from the fixtures. Finally it yields, so that all tests that explicitly use the ``app`` fixtures have access to an application context. See: http://flask.pocoo.org/docs/0.12/appcontext/. """ app = create_app() # app.config.update({'DEBUG': True}) with app.app_context(): # Celery task imports must be local, otherwise their # configuration would use the default pickle serializer. from inspirehep.modules.migrator.tasks import migrate_from_file db.drop_all() drop_alembic_version_table() alembic = Alembic(app=app) alembic.upgrade() _es = app.extensions['invenio-search'] list(_es.delete(ignore=[404])) list(_es.create(ignore=[400])) init_all_storage_paths() init_users_and_permissions() migrate_from_file( './inspirehep/demosite/data/demo-records-acceptance.xml.gz', wait_for_results=True) es.indices.refresh('records-hep') yield app
def setup_db(app): alembic = Alembic(app) alembic.upgrade()
from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic from flask_login import LoginManager from cachelib.simple import SimpleCache db = SQLAlchemy() alembic = Alembic() cache = SimpleCache() login_manager = LoginManager() login_manager.login_view = 'home.login' login_manager.session_protection = 'basic' login_manager.login_message = '请登录' login_manager.login_message_category = 'info' @login_manager.user_loader def load_user(user_id): from webapp.models.user_models import User return User.query.get(user_id)
def test_upgrade(app): alembic = Alembic(app) alembic.upgrade() alembic.downgrade(target='a82a46d12408') # fddb3cfe7a9c alembic.upgrade(target='fddb3cfe7a9c') assert 'inspire_prod_records' in _get_table_names() assert 'inspire_prod_records_recid_seq' in _get_sequences() assert 'workflows_audit_logging' in _get_table_names() assert 'workflows_audit_logging_id_seq' in _get_sequences() assert 'workflows_pending_record' in _get_table_names() # cb9f81e8251c alembic.upgrade(target='cb9f81e8251c') assert 'idxgindoctype' in _get_indexes('records_metadata') assert 'idxgintitles' in _get_indexes('records_metadata') assert 'idxginjournaltitle' in _get_indexes('records_metadata') assert 'idxgincollections' in _get_indexes('records_metadata') # cb5153afd839 alembic.downgrade(target='fddb3cfe7a9c') alembic.upgrade(target='cb5153afd839') assert 'workflows_record_sources' in _get_table_names() # d99c70308006 alembic.upgrade(target='d99c70308006') # 53e8594bc789 alembic.upgrade(target='53e8594bc789') # 402af3fbf68b alembic.upgrade(target='402af3fbf68b') assert 'inspire_prod_records' not in _get_table_names() assert 'inspire_prod_records_recid_seq' not in _get_sequences() assert 'legacy_records_mirror' in _get_table_names() assert 'legacy_records_mirror_recid_seq' in _get_sequences() # 17ff155db70d alembic.upgrade(target="17ff155db70d") # Not checking as it only adds or modifies columns # f9ea5752e7a5 alembic.upgrade(target="f9ea5752e7a5") # Not checking as it only adds or modifies columns # eaab22c59b89 alembic.upgrade(target="eaab22c59b89") # 2f5368ff6d20 alembic.upgrade(target="2f5368ff6d20") # TODO Create proper tests for 2f5368ff6d20, eaab22c59b89, f9ea5752e7a5, # 17ff155db70d # 0bc0a6ee1bc0 alembic.upgrade(target='0bc0a6ee1bc0') assert 'ix_records_metadata_json_referenced_records' in _get_indexes( 'records_metadata')
def test_downgrade(isolated_app): alembic = Alembic(isolated_app) alembic.upgrade() # downgrade 0bc0a6ee1bc0 == downgrade to 2f5368ff6d20 alembic.downgrade(target='2f5368ff6d20') assert 'ix_records_metadata_json_referenced_records' not in _get_indexes( 'records_metadata') # 2f5368ff6d20 # TODO |Create proper tests for 2f5368ff6d20, eaab22c59b89, f9ea5752e7a5 # TODO | and 17ff155db70d alembic.downgrade(target="eaab22c59b89") # eaab22c59b89 alembic.downgrade(target="f9ea5752e7a5") # f9ea5752e7a5 alembic.downgrade(target="17ff155db70d") # 17ff155db70d alembic.downgrade(target="402af3fbf68b") # 402af3fbf68b alembic.downgrade(target='53e8594bc789') # 53e8594bc789 alembic.downgrade(target='d99c70308006') assert 'inspire_prod_records' in _get_table_names() assert 'inspire_prod_records_recid_seq' in _get_sequences() assert 'legacy_records_mirror' not in _get_table_names() assert 'legacy_records_mirror_recid_seq' not in _get_sequences() # d99c70308006 alembic.downgrade(target='cb9f81e8251c') alembic.downgrade(target='cb5153afd839') # cb9f81e8251c & cb5153afd839 alembic.downgrade(target='fddb3cfe7a9c') assert 'idxgindoctype' not in _get_indexes('records_metadata') assert 'idxgintitles' not in _get_indexes('records_metadata') assert 'idxginjournaltitle' not in _get_indexes('records_metadata') assert 'idxgincollections' not in _get_indexes('records_metadata') assert 'workflows_record_sources' not in _get_table_names() # fddb3cfe7a9c alembic.downgrade(target='a82a46d12408') assert 'inspire_prod_records' not in _get_table_names() assert 'inspire_prod_records_recid_seq' not in _get_sequences() assert 'workflows_audit_logging' not in _get_table_names() assert 'workflows_audit_logging_id_seq' not in _get_sequences() assert 'workflows_pending_record' not in _get_table_names()
def register_db(app: Flask) -> Flask: from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app.db = SQLAlchemy(app) Alembic(app) return app
def test_downgrade(inspire_app): alembic = Alembic(current_app) alembic.downgrade(target="318758a589d5") assert "cds_runs" not in _get_table_names() assert "enum_cds_run_status" not in _get_custom_enums() assert "ix_cds_runs_status_date" not in _get_indexes("cds_runs") alembic.downgrade(target="49a436a179ac") assert "idx_object" in _get_indexes("pidstore_pid") assert "object_type, object_uuid" in _get_index_definition( "pidstore_pid", "idx_object" ) alembic.downgrade(target="c9f31d2a189d") assert "ix_inspire_pidstore_redirect_new_pid_id" not in _get_indexes( "inspire_pidstore_redirect" ) assert "ix_inspire_pidstore_redirect_original_pid_id" not in _get_indexes( "inspire_pidstore_redirect" ) assert "inspire_pidstore_redirect" not in _get_table_names() alembic.downgrade(target="020b99d0beb7") assert "ix_experiment_literature_literature_uuid" not in _get_indexes( "experiment_literature" ) assert "ix_experiment_literature_experiment_uuid" not in _get_indexes( "experiment_literature" ) assert "experiment_literature" not in _get_table_names() alembic.downgrade(target="8ba47044154a") assert "ix_records_authors_id_type_record_id" not in _get_indexes("records_authors") alembic.downgrade(target="5a0e2405b624") assert "ix_records_citations_cited_id_citation_type" not in _get_indexes( "records_citations" ) assert "ix_records_citations_citer_id_citation_type" not in _get_indexes( "records_citations" ) alembic.downgrade(target="595c36d68964") assert _check_column_in_table("records_citations", "is_self_citation") is False alembic.downgrade(target="cea5fa2e5d2c") assert "records_authors" not in _get_table_names() assert "ix_records_citations_cited_id" in _get_indexes("records_citations") assert "ix_records_citations_cited_id_citer_id" not in _get_indexes( "records_citations" ) alembic.downgrade("b0cdab232269") assert "institution_literature" not in _get_table_names() assert "ix_institution_literature_literature_uuid" not in _get_indexes( "institution_literature" ) assert "ix_institution_literature_institution_uuid" not in _get_indexes( "institution_literature" ) alembic.downgrade("e5e43ad8f861") assert "idx_pidstore_pid_pid_value" not in _get_indexes("pidstore_pid") alembic.downgrade(target="f563233434cd") assert "enum_conference_to_literature_relationship_type" not in _get_custom_enums() assert "conference_literature" not in _get_table_names() assert "ix_conference_literature_literature_uuid" not in _get_indexes( "conference_literature" ) assert "ix_conference_literature_conference_uuid" not in _get_indexes( "conference_literature" ) alembic.downgrade(target="788a3a61a635") assert "idx_pid_provider" not in _get_indexes("pidstore_pid") alembic.downgrade(target="dc1ae5abe9d6") assert "idx_pid_provider" in _get_indexes("pidstore_pid") alembic.downgrade(target="c6570e49b7b2") assert "records_citations" in _get_table_names() assert "ix_records_citations_cited_id" in _get_indexes("records_citations") alembic.downgrade(target="5ce9ef759ace") assert "record_citations" in _get_table_names() assert "records_citations" not in _get_table_names() assert "ix_records_citations_cited_id" not in _get_indexes("record_citations") assert "idx_citations_cited" in _get_indexes("record_citations") alembic.downgrade(target="b646d3592dd5") assert "ix_legacy_records_mirror_last_updated" not in _get_indexes( "legacy_records_mirror" ) assert "ix_legacy_records_mirror_valid_collection" not in _get_indexes( "legacy_records_mirror" ) assert "legacy_records_mirror" not in _get_table_names() alembic.downgrade(target="7be4c8b5c5e8") assert "idx_citations_cited" not in _get_indexes("record_citations") assert "record_citations" not in _get_table_names()