def try_create_connection( connection_string, wait_for_db, logger, echo: bool = False, reflections: bool = True) -> Tuple[Connection, Engine]: engine = create_engine(connection_string, echo=echo) if reflections: DeferredReflection.prepare(engine) if wait_for_db == 0: max_wait = float('inf') else: max_wait = time.clock_gettime(time.CLOCK_MONOTONIC) + wait_for_db for timeout in chain([1, 2, 5, 10, 30], repeat(60)): try: conn = engine.connect() return conn, engine except OperationalError: # Important: Use %r to print the URL, passwords are hidden by the # __repr__ of sqlalchemy.engine.URL logger.warn("Could not connect to database %r", engine.url) timeout = min(timeout, max_wait - time.clock_gettime(time.CLOCK_MONOTONIC)) if timeout > 0: logger.info("Waiting for %d seconds", timeout) time.sleep(timeout) else: raise
def server_run(args): app = make_app(args.debug) wait_for_db: bool = args.wait_for_database connection_string = get_connection_string() connection = try_create_connection(connection_string, wait_for_db, app.logger) state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() @app.before_request def get_time(): g.request_time = time.time() @app.teardown_request def time_response(exception=None): request_time = g.pop('request_time', None) if request_time: time_taken = time.time() - request_time if time_taken > 0.5: app.logger.warn( "Response took {duration} seconds for request {path}". format(path=request.full_path, duration=time_taken)) engine = create_engine(connection_string, echo=args.profile) set_scoped_session( scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) def lookup_translation(): ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'pycroft_translations', None) if translations is None: translations = Translations() for module in (pycroft, web): os.path.dirname(module.__file__) dirname = os.path.join(ctx.app.root_path, 'translations') translations.merge(Translations.load(dirname, [get_locale()])) ctx.pycroft_translations = translations return translations set_translation_lookup(lookup_translation) app.config.from_pyfile('flask.cfg') if args.profile: app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) app.run(debug=args.debug, port=args.port, host=args.host, threaded=True)
def setup(): global engine, connection, _setup_stack _setup_stack += 1 if _setup_stack > 1: return try: uri = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLalchemy connection string.") engine = create_engine(uri, poolclass=SingletonThreadPool) connection = engine.connect() drop_db_model(connection) create_db_model(connection)
def setup(): global engine, connection, _setup_stack _setup_stack += 1 if _setup_stack > 1: return try: uri = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLalchemy connection string.") engine = create_engine(uri, poolclass=SingletonThreadPool) connection = engine.connect() drop_db_model(connection) create_db_model(connection)
def setup(): global engine, connection, _setup_stack if _setup_stack > 0: return try: uri = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLalchemy connection string.") engine = create_engine(uri, poolclass=SingletonThreadPool, future=True) connection = engine.connect() drop_db_model(connection) create_db_model(connection) connection.commit() DeferredReflection.prepare(engine) _setup_stack += 1
def establish_and_return_session(connection_string): engine = create_engine(connection_string) set_scoped_session(scoped_session(sessionmaker(bind=engine))) return global_session # from pycroft.model.session
```python from helpers.interactive import * ``` This automatically imports all ORM classes plus the `config` object, and initializes the session. """ import os from flask import _request_ctx_stack from sqlalchemy.orm import scoped_session, sessionmaker from pycroft.model import create_engine from pycroft.model.session import set_scoped_session from pycroft.model._all import * from pycroft import config connection_string = os.environ['PYCROFT_DB_URI'] engine = create_engine(connection_string, echo=True) def setup(): # TODO: don't set a scoped session, just a regular one set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) setup()
def server_run(args): app = make_app(args.debug) try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) if args.wait_for_database == 0: max_wait = float('inf') else: max_wait = time.clock_gettime(time.CLOCK_MONOTONIC) + args.wait_for_database for timeout in chain([1, 2, 5, 10, 30], repeat(60)): try: connection = engine.connect() break except OperationalError: # Important: Use %r to print the URL, passwords are hidden by the # __repr__ of sqlalchemy.engine.URL app.logger.warn("Could not connect to database %r", engine.url) timeout = min(timeout, max_wait - time.clock_gettime(time.CLOCK_MONOTONIC)) if timeout > 0: app.logger.info("Waiting for %d seconds", timeout) time.sleep(timeout) else: raise state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() print("If you're running in a docker setup, the port may differ" " from what is given below." " It is probably http://0.0.0.0:5001") @app.before_request def get_time(): g.request_time = time.time() @app.teardown_request def time_response(exception=None): time_taken = time.time() - g.request_time if time_taken > 0.5: app.logger.warn( "Response took {duration} seconds for request {path}".format( path=request.full_path, duration=time_taken)) engine = create_engine(connection_string, echo=args.profile) set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) def lookup_translation(): ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, 'pycroft_translations', None) if translations is None: translations = Translations() for module in (pycroft, web): os.path.dirname(module.__file__) dirname = os.path.join(ctx.app.root_path, 'translations') translations.merge(Translations.load(dirname, [get_locale()])) ctx.pycroft_translations = translations return translations set_translation_lookup(lookup_translation) app.config.from_pyfile('flask.cfg') if args.profile: app.config['PROFILE'] = True app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) app.run(debug=args.debug, port=args.port, host=args.host, threaded=True)
def establish_and_return_session(connection_string): engine = create_engine(connection_string) set_scoped_session(scoped_session(sessionmaker(bind=engine))) return global_session # from pycroft.model.session