def testserver(tmux, livereload, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app extra_files = [from_project_root("flask_app", "app.yml")] app = create_app({ 'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy' }) logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() logbook.compat.redirect_logging() if livereload: from livereload import Server s = Server(app) for filename in extra_files: s.watch(filename) s.watch('flask_app') for filename in ['webapp.js', 'vendor.js', 'webapp.css']: s.watch(os.path.join('static', 'assets', filename), delay=1) s.serve(port=port, liveport=35729) else: app.run(port=port, extra_files=extra_files)
def wait(num_retries=60, retry_sleep_seconds=1): import sqlalchemy from flask_app.app import create_app app = create_app() uri = app.config['SQLALCHEMY_DATABASE_URI'] for retry in xrange(num_retries): logbook.info( "Testing database connection... (retry {0}/{1})", retry + 1, num_retries) if retry > 0: time.sleep(retry_sleep_seconds) try: sqlalchemy.create_engine(uri).connect() except sqlalchemy.exc.OperationalError as e: if 'does not exist' in str(e): break logbook.error( "Ignoring OperationError {0} (db still not availalbe?)", e) except Exception as e: logbook.error( "Could not connect to database ({0.__class__}: {0}. Going to retry...", e, exc_info=True) else: break else: raise RuntimeError("Could not connect to database") logbook.info("Database connection successful")
def main(verbose, quiet): from _benchmark_queries import queries with logbook.NullHandler(), logbook.StreamHandler(sys.stderr, level=logbook.CRITICAL-verbose+quiet, bubble=False): loopback = FlaskLoopback(create_app()) loopback.activate_address((_root_address, 80)) num_attempts = 5 for obj, query in queries: times = [] has_error = False print(obj, '|', click.style(query, fg='cyan'), '--') for i in range(num_attempts): start_time = time.time() resp = requests.get(_root_url.add_path('/rest').add_path(obj).add_query_param('search', query).add_query_param('page_size', 25)) end_time = time.time() if resp.status_code == requests.codes.internal_server_error: print('\t', click.style('Timeout', fg='red')) has_error=True break else: resp.raise_for_status() times.append(end_time - start_time) if not has_error: print('\t', len(resp.json()[obj]), 'results --', '(Out of {}) Best: {:.03}s Avg: {:.03}s Worst: {:.03}s'.format(num_attempts, min(times), sum(times) / len(times), max(times)))
def webapp(request): returned = Webapp(app.create_app()) returned.app.config["SECRET_KEY"] = "testing_key" returned.app.config["TESTING"] = True returned.activate() request.addfinalizer(returned.deactivate) return returned
def drop(): from flask_app.app import create_app from flask_app.models import db app = create_app() with app.app_context(): db.drop_all() db.engine.execute('DROP TABLE IF EXISTS alembic_version')
def mailboxer_url(request, db_engine): loopback = FlaskLoopback(create_app()) hostname = str(uuid.uuid1()) loopback.activate_address((hostname, 80)) @request.addfinalizer def close(): loopback.deactivate_address((hostname, 80)) return URL("http://{0}".format(hostname))
def app(): """An application for the tests.""" _app = create_app('tests.settings') ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def _migrate_context(): from flask_app.app import create_app from flask_app.models import db from flask.ext import migrate app = create_app() migrate.Migrate(app, db) with app.app_context(): yield migrate
def status(): app = create_app() with app.app_context(): replica = models.Replication.query.first() print("Found replica", replica) with _timing(f"Fetching tests to replicate..."): tests = list( models.db.session.execute( replications._get_tests_to_replicate_query(replica))) print(f"Found {len(tests)} to replicate. First one is {tests[0]}")
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 task(name): from flask_app import tasks from flask_app.app import create_app task = getattr(tasks, name, None) if task is None: click.echo('Could not find task named {}'.format(task)) raise click.Abort() with create_app().app_context(): task()
def testserver(tmux, livereload, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy'}) extra_files=[ from_project_root("flask_app", "app.yml") ] app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy'}) if livereload: from livereload import Server s = Server(app) for filename in extra_files: s.watch(filename) s.watch('flask_app') logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() s.serve(port=port, liveport=35729) else: app.run(port=port, extra_files=extra_files)
def list(): from flask_app.app import create_app from flask_app import models app = create_app() with app.app_context(): for user in models.User.query.all(): tokens = user.run_tokens.all() if not tokens: continue print(user.email, tokens[0].token)
def shell(): from flask_app.app import create_app from flask_app import models app = create_app({'SQLALCHEMY_ECHO': True}) with app.app_context(): interact({ 'app': app, 'models': models, 'db': models.db, })
def shell(): from flask_app.app import create_app from flask_app import models app = create_app() with app.app_context(): interact({ 'app': app, 'models': models, 'db': models.db, })
def status(): app = create_app() with app.app_context(): replica = models.Replication.query.first() print("Found replica", replica) with _timing(f"Fetching tests to replicate..."): tests = list( models.db.session.execute( replications._get_tests_to_replicate_query(replica) ) ) print(f"Found {len(tests)} to replicate. First one is {tests[0]}")
def testserver(tmux, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app extra_files=[ from_project_root("flask_app", "app.yml") ] app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy'}) logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() logbook.compat.redirect_logging() app.run(port=port, extra_files=extra_files, use_reloader=False)
def _temporary_db(): from flask_app.app import create_app from flask_app import models from _lib.db import _migrate_context subprocess.check_call('createdb {0}'.format(APP_NAME), shell=True) app = create_app() with _migrate_context(app) as migrate: migrate.upgrade() yield with app.app_context(): models.db.drop_all()
def testserver(tmux, livereload, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy'}) extra_files=[ from_project_root("flask_app", "app.yml") ] app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy'}) if livereload: from livereload import Server s = Server(app) for filename in extra_files: s.watch(filename) s.watch('flask_app') for filename in ['webapp.js', 'vendor.js', 'webapp.css']: s.watch(os.path.join('static', 'assets', filename), delay=1) logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() logbook.compat.redirect_logging() s.serve(port=port, liveport=35729) else: app.run(port=port, extra_files=extra_files)
def _get_client_context(): from flask_app.app import create_app from flask.ext.loopback import FlaskLoopback from backslash import Backslash as BackslashClient app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy'}) with app.app_context(): address = str(uuid4()) loopback = FlaskLoopback(app) loopback.activate_address((address, 80)) try: yield BackslashClient('http://{0}'.format(address)) finally: loopback.deactivate_address((address, 80))
def task(name, defer): from flask_app import tasks from flask_app.app import create_app task = getattr(tasks, name, None) if task is None: click.echo('Could not find task named {}'.format(task)) raise click.Abort() with create_app().app_context(), logbook.StderrHandler(level='DEBUG'): if defer: task.delay() else: task()
def create(user_email): from flask_app.app import create_app from flask_app import models from flask_app.auth import get_or_create_user from flask_app.blueprints.runtoken import create_new_runtoken app = create_app() with app.app_context(): user = get_or_create_user({'email': user_email}) if user.run_tokens.all(): print('User', user_email, 'already has tokens. Skipping...') return token = create_new_runtoken(user) print('Created token', token, 'for', user_email) models.db.session.commit()
def testserver(tmux, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app extra_files = [from_project_root("flask_app", "app.yml")] app = create_app({ 'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy' }) logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() logbook.compat.redirect_logging() app.run(port=port, extra_files=extra_files, use_reloader=False)
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 db_engine(request): if request.config.getoption("--setup-db"): tmpdir = tempfile.mkdtemp() subprocess.check_call("pg_ctl init -D {0} -w".format(tmpdir), shell=True) subprocess.check_call("pg_ctl start -D {0} -w".format(tmpdir), shell=True) @request.addfinalizer def finalize(): subprocess.check_call("pg_ctl stop -D {0} -w -m immediate".format(tmpdir), shell=True) shutil.rmtree(tmpdir) subprocess.check_call("createdb mailboxer", shell=True) with create_app().app_context(): models.db.session.close() models.db.drop_all() models.db.create_all()
def ensure(): from flask_app.app import create_app from flask_app.models import db app = create_app() uri = app.config['SQLALCHEMY_DATABASE_URI'] match = _DATABASE_URI_RE.match(uri) if not match: logbook.error("Don't know how to create a database of type {}", uri) sys.exit(-1) if match.group('db_type') == 'sqlite': _create_sqlite(match.group('db')) elif match.group('db_type') == 'postgresql': _create_postgres(match) logbook.info("DB successfully created")
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 testserver(livereload, port): from flask_app.app import create_app os.environ['CONFIG_DIRECTORY'] = from_project_root("conf.d") extra_files=[ from_project_root("flask_app", "app.yml") ] app = create_app({'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy'}) if livereload: from livereload import Server s = Server(app) for filename in extra_files: s.watch(filename) s.watch('flask_app') s.serve(port=port, liveport=35729) else: app.run(port=port, extra_files=extra_files)
def setUp(self) -> None: # NOTE: IF you remove the following, make sure to remove the shutil.rmtree call # in tearDown() as well. super().setUp() with mock.patch.dict( os.environ, { "PROJECT_DATA_DIRECTORY": tempfile.mkdtemp(prefix="project_data_") }, ): app = create_app(logging_level=logging.DEBUG) app.config["TESTING"] = True app.config["DEBUG"] = True # simulate `with app:` self._app_context = app.app_context() self._app_context.push()
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 db_engine(request): if request.config.getoption("--setup-db"): tmpdir = tempfile.mkdtemp() subprocess.check_call("pg_ctl init -D {0} -w".format(tmpdir), shell=True) subprocess.check_call("pg_ctl start -D {0} -w".format(tmpdir), shell=True) @request.addfinalizer def finalize(): subprocess.check_call( "pg_ctl stop -D {0} -w -m immediate".format(tmpdir), shell=True) shutil.rmtree(tmpdir) subprocess.check_call("createdb mailboxer", shell=True) with create_app().app_context(): models.db.session.close() models.db.drop_all() models.db.create_all()
def _create_flask_app(): global _cached_app global _cached_config if _cached_app is None: returned = _cached_app = app.create_app({ #'SQLALCHEMY_DATABASE_URI': 'postgresql://127.0.0.1/backslash-ut', 'SECRET_KEY': 'testing-key', 'TESTING': True, 'SECURITY_PASSWORD_SALT': 'testing_salt', 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSON_SORT_KEYS': False, }) _cached_config = returned.config.copy() returned.extensions['security'].password_salt = returned.config[ 'SECURITY_PASSWORD_SALT'] else: returned = _cached_app returned.config.update(_cached_config.copy()) return returned
def testserver(tmux, livereload, port): if tmux: return _run_tmux_frontend(port=port) from flask_app.app import create_app extra_files = [from_project_root("flask_app", "app.yml")] app = create_app({ 'DEBUG': True, 'TESTING': True, 'SECRET_KEY': 'dummy', 'SECURITY_PASSWORD_SALT': 'dummy' }) if livereload: from livereload import Server s = Server(app) for filename in extra_files: s.watch(filename) s.watch('flask_app') logbook.StreamHandler(sys.stderr, level='DEBUG').push_application() s.serve(port=port, liveport=35729) else: app.run(port=port, extra_files=extra_files)
def _create_flask_app(): global _cached_app global _cached_config if _cached_app is None: returned = _cached_app = app.create_app( { #'SQLALCHEMY_DATABASE_URI': 'postgresql://127.0.0.1/backslash-ut', "SECRET_KEY": "testing-key", "TESTING": True, "SECURITY_PASSWORD_SALT": "testing_salt", "JSONIFY_PRETTYPRINT_REGULAR": False, "JSON_SORT_KEYS": False, } ) _cached_config = returned.config.copy() returned.extensions["security"].password_salt = returned.config["SECURITY_PASSWORD_SALT"] else: returned = _cached_app returned.config.update(_cached_config.copy()) return returned
def flask_app(): return app.create_app()
import sys from flask import current_app sys.path.insert(0, "/") from flask_app.app import create_app application = create_app('default') if __name__ == "__main__": application.run()
#!/usr/bin/env python import os import flask_app from flask_app import app from flask_app.app import create_app, db from flask_app.app.models import User, Book, Read, Keyword, Book_keyword from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand import flask.ext.whooshalchemy #from flask_alembic.cli.script import manager as alembic_manager app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) application = create_app(os.getenv('FLASK_CONFIG') or 'default') def make_shell_context(): return dict(app=app, db=db, User=User, Book=Book, Read=Read, Keyword=Keyword, Book_Keyword=Book_keyword) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) #manager.add_command('db', alembic_manager) if __name__ == '__main__': manager.run()
def app() -> Flask: return create_app({"TESTING": True, "FAILED_LOGIN_DELAY_BASE": 0})
def webapp(): return app.create_app()
def webapp(): from flask.ext import login return app.create_app()
# -*- coding: utf-8 -*- """Create an application instance.""" from flask_app.app import create_app app = create_app()
from flask_app import app as flask_app app = flask_app.create_app() if __name__ == "__main__": app.run(debug=app.config["DEBUG"], host=app.config["HOST_IP"])