def _setup_app_db(app): """ Setup database service for given MyDojo application. :param mydojo.base.MyDojoApp app: MyDojo application to be modified. :return: Modified MyDojo application :rtype: mydojo.base.MyDojoApp """ # Initialize database service and register it among the application resources # for possible future use. sqldb = mydojo.db.SQLDB sqldb.init_app(app) app.set_resource(mydojo.const.RESOURCE_SQLDB, sqldb) # Initialize database migration service and register it among the application # resources for possible future use. migrate = flask_migrate.Migrate( app=app, db=sqldb, directory=os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'migrations'))) app.set_resource(mydojo.const.RESOURCE_MIGRATE, migrate) app.logger.debug("MyDojo: Connected to database via SQLAlchemy") return app
def create_app(): app = Flask( __name__, static_url_path="/static", instance_relative_config=True ) GoogleMaps(app, key="AIzaSyADCxm6oxGCYP94Gq7igqtczUDycRvTbJU") # load configuration configMode = os.environ.get("app_configuration", "Config") app.config.from_object("config." + str(configMode)) with app.app_context(): # database setup from rounded.models import db db.init_app(app) migrate = flask_migrate.Migrate(app, db) firebase.connect() redis.init() # default app related views from rounded.views.controller import views # import other blueprints from rounded.mod_voting.controller import mod_voting # register controller blueprinters app.register_blueprint(views) app.register_blueprint(mod_voting, url_prefix="/voting") return app
def create_app(): app = flask.Flask(__name__) app.config.from_pyfile('config.py') db.init_app(app) migrate = flask_migrate.Migrate(app, db) avatars = flask_avatars.Avatars(app) app.register_blueprint(auth_blueprint) app.register_blueprint(main_page_blueprint) app.register_blueprint(user_blueprint) app.register_blueprint(admin_blueprint) login_manager = flask_login.LoginManager() login_manager.init_app(app) login_manager.login_view = 'auth.login' locale.setlocale(locale.LC_ALL, 'russian') @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) @app.shell_context_processor def make_shell_context(): return { 'db': db, "User": User, 'Structure': Structure, 'UserInfo': UserInfo } return app
def configure_db(app): models.db.init_app(app) log = logging.getLogger('ara.webapp.configure_db') log.debug('Setting up database...') if app.config.get('ARA_AUTOCREATE_DATABASE'): with app.app_context(): migrations = app.config['DB_MIGRATIONS'] flask_migrate.Migrate(app, models.db, directory=migrations) config = app.extensions['migrate'].migrate.get_config(migrations) # Verify if the database tables have been created at all inspector = Inspector.from_engine(models.db.engine) if len(inspector.get_table_names()) == 0: log.info('Initializing new DB from scratch') flask_migrate.upgrade(directory=migrations) # Get current alembic head revision script = ScriptDirectory.from_config(config) head = script.get_current_head() # Get current revision, if available connection = models.db.engine.connect() context = MigrationContext.configure(connection) current = context.get_current_revision() if not current: log.info('Unstable DB schema, stamping original revision') flask_migrate.stamp(directory=migrations, revision='da9459a1f71c') if head != current: log.info('DB schema out of date, upgrading') flask_migrate.upgrade(directory=migrations)
def db_upgrade(app): from pgadmin.utils import u_encode, fs_encoding with app.app_context(): flask_migrate.Migrate(app, db) migration_folder = os.path.join( os.path.dirname(os.path.realpath(u_encode(__file__, fs_encoding))), os.pardir, os.pardir, u'migrations') flask_migrate.upgrade(migration_folder)
def configure_extensions(app): #configure sqlite db basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join( basedir, 'database', 'sqlite_db.db') app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False Database.db.init_app(app) #configure flask migrate migrate = flask_migrate.Migrate(app, Database.db)
def _migrate_context(app=None): from flask_app.app import create_app from flask_app.models import db import flask_migrate if app is None: app = create_app() flask_migrate.Migrate(app, db) with app.app_context(): yield flask_migrate
def init(): url = get_url(app.config["DB_USER"], app.config["DB_PASSWORD"], app.config["DB_HOST"], app.config["DB_PORT"], app.config["DB_NAME"]) app.config['SQLALCHEMY_DATABASE_URI'] = url # Track modifications of objects and emit signals, expensive, perhaps disable app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) # See http://piotr.banaszkiewicz.org/blog/2012/06/29/flask-sqlalchemy-init_app/, option 2 db.app = app migrate = flask_migrate.Migrate(app, db)
def docker_start(port, backend_name): from flask_app.app import create_app from flask_app.models import db from flask_app.utils import profiling import flask_migrate import gunicorn.app.base _ensure_conf() app = create_app(config={'PROPAGATE_EXCEPTIONS': True}) profiling.set_backend_name(backend_name) flask_migrate.Migrate(app, db) with app.app_context(): flask_migrate.upgrade() # We only allocate one worker per core, since we have two backends to account for # (both API and UI, not to mention the Rust backend in the future) workers_count = multiprocessing.cpu_count() class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in self.options.items() if key in self.cfg.settings and value is not None]) for key, value in config.items(): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': f'0.0.0.0:{port}', 'workers': workers_count, 'capture_output': True, 'timeout': 70, } logbook.StderrHandler(level=logbook.DEBUG).push_application() if app.config['TESTING']: logbook.warning('Testing mode is active!') StandaloneApplication(app, options).run()
def bdd(init_flask_db): """ All tests under this module will have a database with an up to date scheme At the end of the module the database scheme will be downgraded and upgraded again in the next module to test the database migrations """ with app.app_context(): flask_migrate.Migrate(app, db) migration_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'migrations') flask_migrate.upgrade(directory=migration_dir) yield with app.app_context(): flask_migrate.downgrade(revision='base', directory=migration_dir)
def _connectDb(): app = flask.current_app # Ohne Angabe den Treiber 'mysqldb' verwenden app.config['SQLALCHEMY_DATABASE_URI'] = app.config[ 'SQLALCHEMY_DATABASE_URI'].replace('mysql://', 'mysql+mysqldb://') db = SQLAlchemy(app) rows = db.session.query('1').from_statement(text('SELECT 1')).all() assert len(rows) == 1 and rows[0][0] == 1 # DB Model-Migration setup # https://flask-migrate.readthedocs.io/en/latest/ repoDir = pkg_resources.resource_filename( __name__, app.config['SQLALCHEMY_MIGRATE_REPO']) mg.Migrate(app, db, directory=repoDir) mg.upgrade(revision='head') return db
def docker_start(): from flask_app.app import create_app from flask_app.models import db import flask_migrate import gunicorn.app.base from werkzeug.contrib.fixers import ProxyFix _ensure_conf() app = create_app({'PROPAGATE_EXCEPTIONS': True}) app.wsgi_app = ProxyFix(app.wsgi_app) flask_migrate.Migrate(app, db) with app.app_context(): flask_migrate.upgrade() cpu_count = int(subprocess.check_output('nproc').decode("utf-8").strip()) workers_count = cpu_count * 2 + 1 class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in self.options.items() if key in self.cfg.settings and value is not None]) for key, value in config.items(): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '0.0.0.0:8000', 'workers': workers_count, } logbook.StreamHandler(sys.stdout, level=logbook.DEBUG).push_application() if app.config['DEBUG']: logbook.warning('Debug mode is active!') StandaloneApplication(app, options).run()
def create_app() -> flask.Flask: app = flask.Flask(__name__) app.config.from_object(default_config) app.config.from_envvar('APP_CONFIG_FILE') models.db.init_app(app) jwt.jwt.init_app(app) mail.mail.init_app(app) flask_cors.CORS(app) flask_migrate.Migrate(app, models.db) logging.basicConfig( level=logging.DEBUG, stream=sys.stdout, ) errors.register_error_handler(app) modules.register_blueprints(app) return app
def docker_start(): from flask_app.app import create_app from flask_app.models import db import flask_migrate import gunicorn.app.base _ensure_conf() app = create_app(config={'PROPAGATE_EXCEPTIONS': True}) flask_migrate.Migrate(app, db) with app.app_context(): flask_migrate.upgrade() workers_count = (multiprocessing.cpu_count() * 2) + 1 class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in self.options.items() if key in self.cfg.settings and value is not None]) for key, value in config.items(): self.cfg.set(key.lower(), value) def load(self): return self.application options = { 'bind': '0.0.0.0:8000', 'workers': workers_count, 'capture_output': True, } logbook.StderrHandler(level=logbook.DEBUG).push_application() if app.config['TESTING']: logbook.warning('Testing mode is active!') StandaloneApplication(app, options).run()
def configure_db(app): """ 0.10 is the first version of ARA that ships with a stable database schema. We can identify a database that originates from before this by checking if there is an alembic revision available. If there is no alembic revision available, assume we are running the first revision which contains the latest state of the database prior to this. """ models.db.init_app(app) log = logging.getLogger('ara.webapp.configure_db') log.debug('Setting up database...') if app.config.get('ARA_AUTOCREATE_DATABASE'): with app.app_context(): migrations = app.config['DB_MIGRATIONS'] flask_migrate.Migrate(app, models.db, directory=migrations) config = app.extensions['migrate'].migrate.get_config(migrations) # Verify if the database tables have been created at all inspector = Inspector.from_engine(models.db.engine) if len(inspector.get_table_names()) == 0: log.info('Initializing new DB from scratch') flask_migrate.upgrade(directory=migrations) # Get current alembic head revision script = ScriptDirectory.from_config(config) head = script.get_current_head() # Get current revision, if available connection = models.db.engine.connect() context = MigrationContext.configure(connection) current = context.get_current_revision() if not current: log.info('Unstable DB schema, stamping original revision') flask_migrate.stamp(directory=migrations, revision='da9459a1f71c') if head != current: log.info('DB schema out of date, upgrading') flask_migrate.upgrade(directory=migrations)
def init_app(app): db.init_app(app) # Setup migrations migrations_dir = os.path.abspath( os.path.join(app.root_path, '..', 'migrations')) flask_migrate.Migrate(app, db, directory=migrations_dir) with app.app_context(): if os.path.isdir(migrations_dir): try: flask_migrate.upgrade() except Exception as e: logger.error('Migrations failure: {}'.format(e)) else: flask_migrate.init() @app.before_request def setup_request(): flask.g.db = app.db return db
def test_database(): app = NodeDefender.app app.config.update(SQLALCHEMY_DATABASE_URI=get_uri()) db = NodeDefender.db.sql.load(app) folder = NodeDefender.config.migrations_folder migrate = flask_migrate.Migrate(app, db, folder) try: init_migrations(app) except alembic.util.exc.CommandError: drop_alembic_table(db) remove_migrations_folder(folder) init_migrations(app) try: migrate_database(app) upgrade_database(app) except Exception: pass return True
def create_app(): """Initialize application.""" app = flask.Flask(__name__) app.config.from_pyfile('config.py', silent=True) db.init_app(app) ma.init_app(app) flask_migrate.Migrate(app, db) client.conf.update(app.config) with app.app_context(): # pylint: disable=import-outside-toplevel from flaskr import error_handlers from flaskr import auth_api from flaskr import feed_api app.register_blueprint(error_handlers.bp) app.register_blueprint(auth_api.bp, url_prefix='/api/v1/auth') app.register_blueprint(feed_api.bp, url_prefix='/api/v1/feed') app.add_url_rule('/', endpoint='index') return app
# Rate limiter limiter = limiter.LimitWraperFactory() # Application translation babel = flask_babel.Babel() @babel.localeselector def get_locale(): translations = list(map(str, babel.list_translations())) return flask.request.accept_languages.best_match(translations) # Proxy fixer class PrefixMiddleware(object): def __call__(self, environ, start_response): prefix = environ.get('HTTP_X_FORWARDED_PREFIX', '') if prefix: environ['SCRIPT_NAME'] = prefix return self.app(environ, start_response) def init_app(self, app): self.app = fixers.ProxyFix(app.wsgi_app) app.wsgi_app = self proxy = PrefixMiddleware() # Data migrate migrate = flask_migrate.Migrate()
['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').rstrip() _config = ProviderConfiguration( app.config['OIDC_ISSUER'], client_metadata=ClientMetadata( app.config['OIDC_CLIENT_CONFIG']['client_id'], app.config['OIDC_CLIENT_CONFIG']['client_secret'])) auth = OIDCAuthentication({'default': _config}, app) # Get s3 bucket for use in functions and templates s3_bucket = get_bucket(app.config["S3_URL"], app.config["S3_KEY"], app.config["S3_SECRET"], app.config["BUCKET_NAME"]) # Database setup db = SQLAlchemy(app) migrate = flask_migrate.Migrate(app, db) # Import db models after instantiating db object from audiophiler.models import File, Harold, Auth # Create CSHLDAP connection ldap = CSHLDAP(app.config["LDAP_BIND_DN"], app.config["LDAP_BIND_PW"]) # Import ldap functions after creating ldap conn from audiophiler.ldap import ldap_is_eboard, ldap_is_rtp # Disable SSL certificate verification warning requests.packages.urllib3.disable_warnings() @app.route("/")
import flask_bcrypt as _fb import flask_migrate as _fm import flask_sqlalchemy as _fs import json db = _fs.SQLAlchemy() migrate = _fm.Migrate(db=db) bcrypt = _fb.Bcrypt() def init_app(app, **kwargs): db.app = app db.init_app(app) migrate.init_app(app) from sqlalchemy.inspection import inspect class Serializer(object): def serialize(self): return {c: getattr(self, c) for c in inspect(self).attrs.keys()} @staticmethod def serialize_list(l): return [m.serialize() for m in l] from .example import ExampleData
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import import structlog import os import flask import flask_migrate import flask_sqlalchemy logger = structlog.get_logger('releng_common.db') db = flask_sqlalchemy.SQLAlchemy() migrate = flask_migrate.Migrate(db=db) def init_app(app): db.init_app(app) # Check every table starts with app_name for table_name in db.metadata.tables.keys(): if not table_name.startswith(app.name): raise Exception('DB table {} should start with {}'.format( table_name, app.name)) # noqa # Setup migrations migrations_dir = os.path.abspath( os.path.join(app.root_path, '..', 'migrations')) # Setup migrations
#!/usr/bin/env python import flask_migrate import flask_script from seabus.web.socketio import socketio from seabus.common.database import db from seabus.web.web import create_app as create_web_app from seabus.nmea_listen.listener import listen web_app = create_web_app('Dev') web_manager = flask_script.Manager(web_app) flask_migrate.Migrate(web_app, db) web_manager.add_command('db', flask_migrate.MigrateCommand) @web_manager.command def webdev(): socketio.run( web_app, host='0.0.0.0', port=5000, debug=True, use_reloader=True, ) @web_manager.command def webprod(): web_app.config.from_object('seabus.web.config.Prod') socketio.run(
import flask_migrate from allamericanregress import config import random import logging import os import alembic logger = logging.getLogger(__name__) # hack to get a reference to the templates directory within the package if config.FROZEN: tmpl_dir = os.path.join(config.MODULE_PATH, 'templates') static_dir = os.path.join(config.MODULE_PATH, 'static') else: tmpl_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'templates') static_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'static') # ========== Flask App ========== app = flask.Flask(__name__, static_url_path='/static', template_folder=tmpl_dir, static_folder=static_dir) # auto reload template engine when template files change app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['SECRET_KEY'] = str(int(random.random() * 100000000000)) # set the database location and protocol app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{config.DB_PATH}' # initialize SQLAlchemy engine db = SQLAlchemy(app) # initialize migration engine migrate = flask_migrate.Migrate(app, db, directory=config.ALEMBIC_PATH)
# SOFTWARE. import logging import os import ssl import click import flask_migrate from flask.cli import FlaskGroup from werkzeug.serving import run_simple from freshmaker import app, conf, db from freshmaker import models migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrations') migrate = flask_migrate.Migrate(app, db, directory=migrations_dir) @click.group(cls=FlaskGroup, create_app=lambda *args, **kwargs: app) def cli(): """Manage freshmaker application""" cli.command('db', flask_migrate.MigrateCommand) def _establish_ssl_context(): if not conf.ssl_enabled: return None # First, do some validation of the configuration attributes = (
import os import flask import flask_login import flask_migrate from flask_sqlalchemy import SQLAlchemy app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'THISISMYSECTERKEY' db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join( os.path.dirname(__file__), 'cv.db') migrate = flask_migrate.Migrate(app, db) login_mng = flask_login.LoginManager(app) # this will help you incase your flask db migrate does not work/ but u can delete it if want with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) from CV_PROJECT import routes, models
app.config['SQLALCHEMY_POOL_RECYCLE'] = 60 # DB = flask_sqlalchemy.SQLAlchemy(app) # migrate = flask_migrate.Migrate(app, DB) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'super-secret' app.config['SECURITY_PASSWORD_HASH'] = 'pbkdf2_sha512' app.config[ 'SECURITY_PASSWORD_SALT'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' app.config['WTF_CSRF_ENABLED'] = False app.config['SECURITY_REGISTERABLE'] = True app.config['SECURITY_TOKEN_MAX_AGE'] = 600 #DB = flask_sqlalchemy.SQLAlchemy(app) DB.init_app(app) migrate = flask_migrate.Migrate(app, DB) # roles_users = DB.Table('roles_users', # DB.Column('user_id', DB.Integer(), DB.ForeignKey('userrole.id')), # DB.Column('role_id', DB.Integer(), DB.ForeignKey('role.id'))) # # # class Role(DB.Model, RoleMixin): # id = DB.Column(DB.Integer(), primary_key=True) # name = DB.Column(DB.String(80), unique=True) # description = DB.Column(DB.String(255)) # # # class Userrole(DB.Model, UserMixin): # id = DB.Column(DB.Integer, primary_key=True) # email = DB.Column(DB.String(255), unique=True)
#!/usr/bin/env python2.7 import buzzwebpanel from buzzwebpanel import db import buzzwebpanel.models import flask_script import flask_migrate manager = flask_script.Manager(buzzwebpanel.app) # Database migrations migrate = flask_migrate.Migrate(buzzwebpanel.app, buzzwebpanel.db) manager.add_command('db', flask_migrate.MigrateCommand) if __name__ == '__main__': manager.run()
def init_app(app): db.init_app(app) flask_migrate.Migrate(app, db, directory='database/migrations')
elif len(config_files) > 1: print 'Ambiguous config argument. Candidates: {0}'.format(', '.join( filename[:-3] for filename in config_files)) elif not app.APP.config.from_pyfile( os.path.join(EISITIRIO_DIR, 'config', config_files[0])): print 'Could not load config file {0}'.format( os.path.join(EISITIRIO_DIR, 'config', config_files[0])) else: return app.APP sys.exit(-1) script.Server.help = 'Run the development server' MIGRATE = migrate.Migrate(app.APP, db.DB) MANAGER = script.Manager(get_app, with_default_commands=False) MANAGER.add_option('config', default=None, help="Configuration file to load before running commands") # MANAGER.add_command('bpython', run_bpython.BpythonCommand) MANAGER.add_command('cron', cron.CronCommand) MANAGER.add_command('fix_graduand_postage', fix_graduand_postage.FixGraduandPostageCommand) MANAGER.add_command('db', migrate.MigrateCommand) MANAGER.add_command('prefill', prefill.PrefillCommand) MANAGER.add_command('run', script.Server) MANAGER.add_command('update_battels', update_battels.UpdateBattelsCommand)