def create_db(): """ Run database initialization :return: """ from flask_migrate import init, migrate, upgrade # initialize migrations migrations_dir = os.path.join(app.config['ROOT_DIR'], 'migrations') if not os.path.exists(migrations_dir): init() # perform database migrations migrate() # migrate database to latest revision upgrade() print("Migrations completed" + "." * 10) # initialize database with default records from app.utils import InitDatabase init_db = InitDatabase() init_db.add_stories() print("Database records added" + "." * 10)
def setUp(self): app_ctx = manager.app.app_context() app_ctx.push() flask_migrate.init() flask_migrate.migrate() flask_migrate.upgrade() app_ctx.pop() manager.app.config['TESTING'] = True self.client = manager.app.test_client()
def deploy(): from flask_migrate import init, migrate, upgrade from app.cities.models import Cities from app.regions.models import Regions from app.users.models import Users init() migrate() upgrade()
def dbupgrade(): try: migrate_dict = Migrate(app, db) migrate(directory=migrate_dict.directory) upgrade(directory=migrate_dict.directory) all_tables = ' <br/>'.join(map(str, db.engine.table_names())) return 'Tables upgraded in database <br/>' + all_tables except Exception as e: return str(e)
def seed(): # os.remove('.db') # shutil.rmtree('migrations') with app.app_context(): init() migrate() upgrade() Room.add(name="test", password="")
def deploy(): from flask_migrate import upgrade, migrate # 把数据库迁移到最新修订版本 migrate() upgrade() # 创建内置用户 User.insert_admin() Attr.init_attr()
def init(): """Run initial deployment tasks.""" from flask_migrate import init, migrate, upgrade # determine the appropriate migration folder migration_path = os.environ.get('MIGRATION_PATH') if not migration_path: migration_path = 'migrations' print('Upgrading from', migration_path) init(migration_path) migrate(migration_path) upgrade(migration_path)
def deploy(): from flask_migrate import upgrade, init, migrate from app.models import User # 把数据库迁移到最新修订版本 , # 在heroku server上创建的目录、文件跟web app根本不在一个环境里。所以,db migration三条命令(init/migrate/uprade)必须在Bash里一并运行完,不能一条条运行 #init() migrate() upgrade() # 让所有用户都关注此用户 User.add_self_follows()
def migrate(self): with plugin_name_migrate(self.__module__): plugindir = current_app.extensions['plugin_manager'].plugin_folder try: migrate(directory=os.path.join(plugindir, 'migrations'), head=self.settings_key) except Exception as e: #presumably this is the initial migration? migrate(directory=os.path.join(plugindir, 'migrations'), version_path=self.resource_filename('migration_versions'), branch_label=self.settings_key)
def migrate_db(): "Upgrade database schema." from zou.app import app with app.app_context(): import zou directory = os.path.join( os.path.dirname(zou.__file__), "migrations" ) flask_migrate.migrate(directory=directory)
def dev_setup(): if config != "development": raise Exception("Don't run dev-setup if not using development config!") db.drop_all() migrate() upgrade() Role.insert_roles() utils.insert_admin() utils.insert_fake_users() utils.insert_fake_posts() utils.insert_fake_comments()
def migrate(self): logger.info('Applying migrations...') directory = str(self.migrate_dir) if not self.migrate_dir.exists(): init(directory) with wsgi.app.app_context(): migrate(directory, message='initial') upgrade(directory) logger.info('SUCCESSFULLY')
def migrate_migrations(): """debug only""" from flask_migrate import migrate if os.path.exists(os.getenv('MIGRATIONS', basedir + '/migrations')): migrate(directory=os.getenv('MIGRATIONS', basedir + '/migrations'), message=str(datetime.utcnow())) print 'migrate database :' + os.getenv('MIGRATIONS', basedir + '/migrations') else: print 'Can\'t find :' + os.getenv('MIGRATIONS', basedir + '/migrations')
def deploy(): from flask_migrate import upgrade, migrate migrate() upgrade() # 创建内置用户 User.insert_admin() Attr.init_attr() AttrOther.init_attr_action() ContactWay.insert_data() Temps.insert_tmeps()
def deploy(): """Run deployment tasks.""" from flask_migrate import init, migrate, upgrade # migrate database to latest revision try: init() except: pass migrate() upgrade()
def init_db(): assert not config.is_production() # not auto migrations in prod # Make the migrations folder if it does not already exist if not path.exists(config.MIGRATION_DIR): fm.init() # Make migrations fm.migrate(config.MIGRATION_DIR) fm.upgrade(config.MIGRATION_DIR) population.populate_study()
def deploy(): """Run deployment task""" from flask_migrate import migrate, upgrade, init # init database init() # create migrations migrate() # update Database upgrade()
def deploy(): from flask_migrate import upgrade from flask_migrate import init from flask_migrate import migrate from model.role import Role from model.user import User init(directory=migrationsdir) migrate(directory=migrationsdir, message='initial migration') upgrade(directory=migrationsdir) # create roles Role.insert_roles() # make all users follow themselives. User.add_self_follows()
def migrate_db(): """ Generate migration files to describe a new revision of the database schema (for development only). """ from zou.app import app with app.app_context(): import zou directory = os.path.join(os.path.dirname(zou.__file__), "migrations") flask_migrate.migrate(directory=directory)
def reset_db_command(): """ clear existing tables and re-initialize database. """ basedir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(basedir, 'migrations') shutil.rmtree(path) # removing the migrations directory... path = os.path.join(basedir, 'app.db') os.remove(path) # remove app.db flask_migrate.init() # reset everything flask_migrate.migrate() flask_migrate.upgrade() click.echo('Database full reset. done.')
def setup(): init() migrate() upgrade() print("Creating roles...") Role.from_csv() print("Creating users...") User.from_csv() print("Committing...") db.session.commit() print("Done!")
def init_db(): from flask_migrate import init, migrate, upgrade init("./test/migrations") with open("./test/migrations/script.py.mako", "r") as f: lines = f.readlines() for i, x in enumerate(lines): if "from alembic import op" in x: lines.insert(i, "import ormtypes\n") break with open("./test/migrations/script.py.mako", "w") as f: f.writelines(lines) migrate("./test/migrations") upgrade("./test/migrations")
def client(): current_dir = os.path.dirname(os.path.abspath(__file__)) sqlite_file_path = os.path.join(current_dir, 'sqlite.db') if os.path.exists(sqlite_file_path): os.remove(sqlite_file_path) delete_all_migrations(current_dir) init_config(test_db_path=os.path.join("sqlite:///" + sqlite_file_path)) app = init_app() open(sqlite_file_path, 'a').close() with app.app_context(): flask_migrate.init() flask_migrate.migrate() flask_migrate.upgrade() yield app.test_client()
def data(room='general'): if 'lost' in (res := db_health())['status']: return res, 400 create_table_instance(room) if request.method == 'POST': if room not in db.engine.table_names(): migrate(message='Added room {}'.format(room)) upgrade() post = tables[room](username=request.form.get('username'), messages=request.form.get('msg')) db.session.add(post) db.session.commit() write_2_file(room) with open(f, "r") as file: content = file.read() return Response(content, mimetype='text/plain')
def UpgradeDB(): """ Mise à jour de la DB """ with app.app_context(): app.logger.info("Migration de la base de donnees...") try : flask_migrate.migrate() except Exception, err : if "Path doesn't exist" in str(err) : app.logger.info("Repertoire Migrations manquant -> Initialisation de flask_migrate maintenant...") flask_migrate.init() flask_migrate.migrate() app.logger.info("Migration ok.") app.logger.info("Upgrade de la base de donnees...") flask_migrate.upgrade() app.logger.info("Upgrade ok.")
def deploy(): """Run deployment tasks.""" from app import create_app,bcrypt app = create_app() app.app_context().push() from models import Role,User from app import db from flask_migrate import upgrade,migrate,init,stamp db.create_all() # create user roles Role.insert_roles() # migrate database to latest revision stamp() migrate() upgrade()
def instantiate_db(app): """Make sure the db is initialized.""" # initialize db with flask_migrate with app.app_context(): try: flask_migrate.init(webapp.config.ALEMBIC_PATH) except alembic.util.exc.CommandError as e: if 'already exists' in str(e): pass else: logger.debug('flask db init failed: %s', e) raise e flask_migrate.migrate(webapp.config.ALEMBIC_PATH) try: logger.debug('flask db upgrade') flask_migrate.upgrade(webapp.config.ALEMBIC_PATH) except Exception as e: logger.debug('flask db upgrade failed: %s', e) raise e
def init(): """ [Re]cretate database, deploy and create three sample users, an image and some battles """ from flask_migrate import init, migrate call(["rm", "-rf", "data-dev.sqlite", "migrations"]) init() migrate() deploy() user_a = User(username='******', email='*****@*****.**', password='******', confirmed=True) user_b = User(username='******', email='*****@*****.**', password='******', confirmed=True) user_c = User(username='******', email='*****@*****.**', password='******', confirmed=True) lenna = Image(name='lenna.png', user=user_a) ducklings = Image(name='ducklings.jpg', user=user_b) flower = Image(name='flower.jpg', user=user_c) battle1 = user_a.challenge(user_b, lenna) battle1.challenge_accepted = True user_c.vote(battle1, "challenger") battle2 = user_a.challenge(user_b, ducklings) battle3 = user_c.challenge(user_a, flower) db.session.add(user_a) db.session.add(user_b) db.session.add(user_c) db.session.add(lenna) db.session.add(battle1) db.session.add(battle2) db.session.add(battle3) db.session.commit()
def reset_db(): print() if os.path.isfile(db_path): print("db file found - deleting...") os.remove(db_path) print("db file deleted!\n") if os.path.isdir(migrations_path): print("migrations found - deleting...") shutil.rmtree(migrations_path) print("migrations deleted!\n") print("setting up the db...") flask_migrate.init() flask_migrate.migrate() flask_migrate.upgrade() print("db has been successfully setup!\n") print("Local setup has successfully been reset!")
def init(): # programmatically initialize db with flask_migrate with app.app_context(): try: # initialize migrations directory and config files flask_migrate.init(config.ALEMBIC_PATH) except alembic.util.exc.CommandError as e: if 'already exists' in str(e): pass else: logger.debug('flask db init failed: %s', e) raise e # detect model diffs and generate migration scripts flask_migrate.migrate(config.ALEMBIC_PATH) try: # logger.debug('flask db upgrade') # perform the migration flask_migrate.upgrade(config.ALEMBIC_PATH) except Exception as e: logger.debug('flask db upgrade failed: %s', e) raise e
def UpgradeDB(): """ Mise à jour de la DB """ with app.app_context(): app.logger.info("Migration de la base de donnees...") try: flask_migrate.migrate(directory=REP_MIGRATIONS) app.logger.info("Migrate - Migration ok.") except SystemExit as e: app.logger.info("SystemQuit -> Erreur dans migration > migrate") app.logger.info(traceback.format_exc()) except Exception as err: app.logger.info("Erreur dans migration > migrate.") app.logger.info(err) app.logger.info("Upgrade de la base de donnees...") try: flask_migrate.upgrade(directory=REP_MIGRATIONS) app.logger.info("Migrate - Upgrade ok.") except SystemExit as e: app.logger.info("SystemQuit -> Erreur dans migration > upgrade.") app.logger.info(traceback.format_exc()) except Exception as err: app.logger.info("Erreur dans migration > upgrade.") app.logger.info(err) # Si la revision n'existe pas if "Can't locate revision" in str(err): app.logger.info("Suppression table alembic_version...") result = db.session.execute( "DROP TABLE IF EXISTS alembic_version;") app.logger.info("Suppression du repertoire migrations...") shutil.rmtree(REP_MIGRATIONS) flask_migrate.init(directory=REP_MIGRATIONS) flask_migrate.migrate() # Mémorisation du nouveau numéro de version dans la DB m = Parametre.query.filter_by(nom="version").first() m.parametre = app.config["VERSION_APPLICATION"] db.session.commit()
def UpgradeDB(): """ Mise à jour de la DB """ with app.app_context(): app.logger.info("Migration de la base de donnees...") try: flask_migrate.migrate(directory=REP_MIGRATIONS) except Exception, err: if "Path doesn't exist" in str(err): app.logger.info( "Repertoire Migrations manquant -> Initialisation de flask_migrate maintenant..." ) flask_migrate.init(directory=REP_MIGRATIONS) flask_migrate.migrate() app.logger.info("Migration ok.") app.logger.info("Upgrade de la base de donnees...") try: flask_migrate.upgrade(directory=REP_MIGRATIONS) app.logger.info("Upgrade ok.") except Exception, err: app.logger.info("Erreur Upgrade.") app.logger.info(err) # Si la revision n'existe pas if "Can't locate revision" in str(err): app.logger.info("Suppression table alembic_version...") result = db.session.execute( "DROP TABLE IF EXISTS alembic_version;") app.logger.info("Suppression du repertoire migrations...") shutil.rmtree(REP_MIGRATIONS) flask_migrate.init(directory=REP_MIGRATIONS) flask_migrate.migrate()
def mmigrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): _tag = DBTag.query.limit(1).first() start_tag = _tag.tag if start_tag: old_table = DownloadRecord.model(start_tag) start_year = int(start_tag[:-2]) start_month = int(start_tag[-2:]) now_year = datetime.utcnow().year now_month = datetime.utcnow().month interval_month = (now_year - start_year) * 12 + (now_month - start_month) for idx in range(interval_month): total_month = start_month + idx record_tag = '{:4d}{:02d}'.format(start_year + total_month // 12, total_month % 12 + 1) old_table = DownloadRecord.model(record_tag) latest_table = DownloadRecord.model() migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None)
def init_db(): """Initialize the database.""" flask_migrate.migrate()
def upgrade_db(): migrate() upgrade()
def db_migrate(c, dir=DEFAULT_MIGRATION_DIR): """ Generate new autofilled migration. """ with app.app_context(): migrate.migrate(directory=dir)