def create(default_data=True, sample_data=False): """ Creates database tables from sqlalchemy models """ from flask.ext.migrate import stamp db.create_all() stamp()
def create_db(): db.create_all() # create the tables for python-social-auth from sqlalchemy import create_engine from social.apps.flask_app.default import models as PSA_models engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) PSA_models.PSABase.metadata.create_all(engine) from .models import Tab, TAB_NAMES # Make sure we have all the tabs in the database. # TODO make this a bit more reliable since it can fail if some tabs are # there and some aren't and we're messing with the order column for i, (tab, tab_name) in enumerate(TAB_NAMES.items()): if Tab.query.filter_by(name=tab).first() is None: t = Tab(name=tab, external_name=tab_name, order=i) db.session.add(t) db.session.commit() with app.app_context(): stamp() print("Database created.")
def action_db_migrate(action=('a', 'start'), debug=False): """Migrate database. This command is responsible for data base migrations. Actions: init - initiates migration module use only once. migrate - creates schema migration. upgrade - upgrades database using schema migrations. Options: - '--debug' use debug configuration """ from flask.ext.migrate import upgrade, init, migrate, stamp, downgrade if debug: app = make_debug(with_debug_layer=False) else: app = make_app() with app.app_context(): if action == 'init': init() elif action == 'migrate': migrate() elif action == 'upgrade': upgrade() elif action == 'stamp': stamp() elif action == 'downgrade': downgrade() else: print('Unknown action')
def create(): """ Initialize the database by creating the necessary tables and indices """ # create all tables and indices db.create_all() # create alembic version table stamp()
def initdb(random_data=False): """Drops and recreates all tables""" print("Dropping tables") db.drop_all() print("Creating tables") db.create_all() stamp(revision='head') if random_data: print("Creating random data") matz = User(email='*****@*****.**', first_name='Matz', last_name='Radloff', is_admin=True) matz.set_password('testpw') db.session.add(matz) db.session.commit() faker = Faker() random_fields = [ {'name': 'Overall Mood', 'type': EntryFieldType.RANGE.value}, {'name': 'Cups of Coffee', 'type': EntryFieldType.INTEGER.value}, {'name': 'Hours of Sleep', 'type': EntryFieldType.INTEGER.value}, {'name': 'Quality of Sleep', 'type': EntryFieldType.RANGE.value}, {'name': 'Comment', 'type': EntryFieldType.STRING.value}, {'name': 'Energy Drinks', 'type': EntryFieldType.INTEGER.value}, {'name': 'Concentration', 'type': EntryFieldType.RANGE.value}, {'name': 'Stray Thougts Intensity', 'type': EntryFieldType.RANGE.value} ] for field in random_fields: new_entry_field = EntryField(name=field['name'], type=field['type'], user_id=matz.id) db.session.add(new_entry_field) db.session.commit() for i in range(150, 0, -1): new_entry = Entry(date=datetime.utcnow() - timedelta(days=i), user_id=matz.id) db.session.add(new_entry) for field in EntryField.query: if field.type == EntryFieldType.STRING.value: content = faker.sentence() elif field.type == EntryFieldType.RANGE.value: content = str(random.randint(0, 10)) elif field.type == EntryFieldType.INTEGER.value: content = str(random.randint(0, 100)) new_answer = EntryFieldAnswer(content=content, entry=new_entry, entry_field=field) db.session.add(new_answer) db.session.commit()
def build_db(): uri = app.config['SQLALCHEMY_DATABASE_URI'] if not uri.startswith('sqlite'): msg = 'This script is intended for sqlite dbs only.\n' msg += 'You should probably use the migration script: ' msg += "'python manage.py db upgrade'" raise Exception(msg) db_file = uri.split('/')[-1] if os.path.exists(db_file): msg = 'The database already exists. If you want to rebuild the ' msg += 'database, you must first remove the file:\n' msg += db_file raise Exception(msg) db.create_all() stamp()
def init_db(emit=False): """ Resets entire database to empty state """ if emit: import logging logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) res = raw_input("You shouldn't probably ever do this in production! Are you" " really, really sure you want to reset the DB? [y/n] ") if res != "y": return else: db.session.commit() db.drop_all() db.create_all() stamp()
def initialize_db(credentials): with app.app_context(): populate_data = True inspector = reflection.Inspector.from_engine(db.engine) table_name = 'events' table_names = inspector.get_table_names() if table_name not in table_names: try: db.create_all() stamp() except: populate_data = False print "Could not create tables. Either database does not exist or tables already created" if populate_data: credentials = credentials.split(":") DataManager.create_super_admin(credentials[0], credentials[1]) populate()
def create(force=False): """Create tables if the database has not been configured yet.""" # Fail if there's an alembic version set engine = db.get_engine(flask.current_app) conn = engine.connect() context = MigrationContext.configure(conn) current_rev = context.get_current_revision() alembic_config = _get_config(directory=migrate_path) script = ScriptDirectory.from_config(alembic_config) latest_rev = script.get_current_head() if current_rev == latest_rev and not force: print(u"You need to run 'evesrp -c config.py db migrate' to " u"migrate to the latest database schema.") else: db.create_all() if current_rev is None: stamp()
def run(self, password, aws): db.drop_all() db.create_all() # WARNING: # if you edit this method, make analogous changes in # kubedock.testutils.fixtures.initial_fixtures # TODO: merge two methods in one now = datetime.utcnow() now.replace(tzinfo=pytz.utc) available_updates = get_available_updates() if available_updates: last_upd = Updates.create(fname=available_updates[-1], status=UPDATE_STATUSES.applied, log='Applied at createdb stage.', start_time=now, end_time=now) db.session.add(last_upd) db.session.commit() add_kubes_and_packages() add_system_settings() add_notifications() add_all_permissions() add_users_and_roles(password) generate_menu(aws) add_restricted_ports() # Fix packages id next val db.engine.execute("SELECT setval('packages_id_seq', 1, false)") stamp()
def create(): database.db.create_all() stamp(revision='head')
def create(): "Creates database tables from sqlalchemy models" db.create_all() stamp()
app.register_blueprint(api) # custom jinja2 filters app.jinja_env.filters['minimal_round'] = minimal_round # db db.init_app(app) db.app = app # db migrations migrate = Migrate(app, db) if pre_alembic_db(): with app.app_context(): # fake the first migration stamp(revision='b9a10d5d63ce') # auto-execute migrations on runtime with app.app_context(): upgrade() # mail mail.init_app(app) # translations babel = Babel(app) # sentry sentry = Sentry(app) @babel.localeselector
print "Initializing..." print "Creating tables..." # db.create_all() upgrade() print "Created tables successfully" tmpPW = common.generate_random_string(8) from flask.ext.bcrypt import generate_password_hash, check_password_hash print "Creating default user..." db.session.add( User("admin", generate_password_hash(tmpPW), common.generate_random_string(32))) db.session.commit() print "Created new user: admin / %s" % (tmpPW) print "-" * 100 elif "Config" not in saTables: # Temporary patch for those who are using depot # version earlier than commit c0a0e1d stamp(revision="710d5081fa7") upgrade() else: # Check for any db updates upgrade()
app.register_blueprint(api) # custom jinja2 filters app.jinja_env.filters['minimal_round'] = minimal_round # db db.init_app(app) db.app = app # db migrations migrate = Migrate(app, db) if pre_alembic_db(): with app.app_context(): # fake the first migration stamp(revision='b9a10d5d63ce') # auto-execute migrations on runtime with app.app_context(): upgrade() # mail mail.init_app(app) # translations babel = Babel(app) # sentry sentry = Sentry(app)
if "Config" not in saTables and "Path" not in saTables: print "-"*100 print "Initializing..." print "Creating tables..." # db.create_all() upgrade() print "Created tables successfully" tmpPW = common.generate_random_string(8) from flask.ext.bcrypt import generate_password_hash, check_password_hash print "Creating default user..." db.session.add(User("admin", generate_password_hash(tmpPW), common.generate_random_string(32))) db.session.commit() print "Created new user: admin / %s"%(tmpPW) print "-"*100 elif "Config" not in saTables: # Temporary patch for those who are using depot # version earlier than commit c0a0e1d stamp(revision="710d5081fa7") upgrade() else: # Check for any db updates upgrade()
from populate_db import populate def _validate_email(email): if not re.match(r'[^@]+@[^@]+\.[^@]+', email): print '\nInvalid email address' sys.exit(1) def _validate_password(password): if len(password) < 4: print '\nPassword should have minimum 4 characters' sys.exit(1) def create_default_user(): print "Your login is 'super_admin'." email = raw_input("Enter email for super_admin : ") _validate_email(email) password = getpass("Enter password for super_admin : ") _validate_password(password) DataManager.create_super_admin(email, password) if __name__ == "__main__": with current_app.app_context(): db.create_all() stamp() create_default_user() populate()