Beispiel #1
0
def db_init(app):
    app.logger.info('Initializing PsqlGraph driver')
    app.db = PsqlGraphDriver(
        host=app.config['PSQLGRAPH']['host'],
        user=app.config['PSQLGRAPH']['user'],
        password=app.config['PSQLGRAPH']['password'],
        database=app.config['PSQLGRAPH']['database'],
        set_flush_timestamps=True,
    )

    app.userdb = SQLAlchemyDriver(app.config['PSQL_USER_DB_CONNECTION'])
    flask_scoped_session(app.userdb.Session, app)

    app.oauth2 = OAuth2Client(**app.config['OAUTH2'])

    app.logger.info('Initializing Signpost driver')
    app.signpost = SignpostClient(
        app.config['SIGNPOST']['host'],
        version=app.config['SIGNPOST']['version'],
        auth=app.config['SIGNPOST']['auth'])
    try:
        app.logger.info('Initializing Auth driver')
        app.auth = AuthDriver(app.config["AUTH_ADMIN_CREDS"], app.config["INTERNAL_AUTH"])
    except Exception:
        app.logger.exception("Couldn't initialize auth, continuing anyway")
Beispiel #2
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('settings.py')
    engine = create_engine(app.config['SQLALCHEMY_DB_URI'], echo=app.config['SQLALCHEMY_ECHO'])
    flask_scoped_session(sessionmaker(bind=engine), app)

    JWTManager(app)

    api = Api(
        app,
        description='OLOLO',
        authorizations={
            'JWT Access': {
                'type': 'apiKey',
                'in': 'header',
                'name': 'Authorization'
            },
            'JWT Refresh': {
                'type': 'apiKey',
                'in': 'header',
                'name': 'Authorization'
            },
        },
    )
    api.add_namespace(auth_namespace)
    api.add_namespace(towns_namespace)
    api.add_namespace(district_namespace)

    return app
 def __create_session(app):
     flask_scoped_session(
         sessionmaker(autocommit=False,
                      autoflush=True,
                      expire_on_commit=False,
                      bind=create_engine(
                          app.config['SQLALCHEMY_DATABASE_URI'],
                          encoding='utf-8')), app)
Beispiel #4
0
def create_app(db_uri: str = "sqlite://"):
    """
    Create a Flask application instance.

    Initializes the database, app routes, and extensions.

    :param db_uri: Database uri
    """
    app = Flask('featuresreq')

    # Intialize the datbase
    engine = create_engine(db_uri)
    session_factory.configure(bind=engine)
    session = flask_scoped_session(session_factory, app)
    app.session = session

    # Register blueprints
    app.register_blueprint(bp)

    # Bootstrap the database models and Clients
    @app.before_first_request
    def bootstrap_client_models():
        Base.metadata.create_all(engine)

        for c in ("a", "b", "c"):
            name = "Client {}".format(c.upper())
            client = session.query(Client).filter(
                func.lower(Client.name) == name.lower()).first()
            if client is None:
                client = Client(name=name)
                session.add(client)
                session.commit()

    return app
Beispiel #5
0
def configure_flask_sqlalchemy_session(app: flask.Flask):
    db_config = app.config['DB_CONFIG']
    session_factory = session_factory_from_config(db_config)
    flask_sa_session = flask_sqlalchemy_session.flask_scoped_session(
        session_factory, app)

    return flask_sa_session
Beispiel #6
0
def app_sessions(app):
    app.url_map.strict_slashes = False
    app.db = SQLAlchemyDriver(app.config["DB"])
    migrate(app.db)
    session = flask_scoped_session(app.db.Session, app)  # noqa
    app.storage_manager = StorageManager(
        app.config["STORAGE_CREDENTIALS"], logger=app.logger
    )
    enabled_idp_ids = app.config["ENABLED_IDENTITY_PROVIDERS"]["providers"].keys()
    # Add OIDC client for Google if configured.
    configured_google = (
        "OPENID_CONNECT" in app.config and "google" in app.config["OPENID_CONNECT"]
    )
    if configured_google:
        app.google_client = GoogleClient(
            app.config["OPENID_CONNECT"]["google"],
            HTTP_PROXY=app.config.get("HTTP_PROXY"),
            logger=app.logger,
        )
    # Add OIDC client for multi-tenant fence if configured.
    configured_fence = (
        "OPENID_CONNECT" in app.config
        and "fence" in app.config["OPENID_CONNECT"]
        and "fence" in enabled_idp_ids
    )
    if configured_fence:
        app.fence_client = OAuthClient(**app.config["OPENID_CONNECT"]["fence"])
    app.session_interface = UserSessionInterface()
    if app.config.get("ARBORIST"):
        app.arborist = ArboristClient(arborist_base_url=app.config["ARBORIST"])
def initialize_database(autoinitialize=True):
    db_url = Configuration.database_url()
    if autoinitialize:
        SessionManager.initialize(db_url)
    session_factory = SessionManager.sessionmaker(db_url)
    _db = flask_scoped_session(session_factory, app)
    app._db = _db

    Configuration.load(_db)
    testing = 'TESTING' in os.environ
    log_level = LogConfiguration.initialize(_db, testing=testing)
    if app.debug is None:
        debug = log_level == 'DEBUG'
        app.debug = debug
    else:
        debug = app.debug
    app.config['DEBUG'] = debug
    _db.commit()
    app.log = logging.getLogger("Metadata web app")
    app.log.info("Application debug mode: %r", app.debug)
    for logger in logging.getLogger().handlers:
        app.log.info("Logs are going to %r", logger)

    # Register an error handler that logs exceptions through the
    # normal logging process and tries to turn them into Problem
    # Detail Documents.
    h = ErrorHandler(app, app.config['DEBUG'])
    @app.errorhandler(Exception)
    def exception_handler(exception):
        return h.handle(exception)
Beispiel #8
0
def init_db(app):
    from app.db import Base
    Base.metadata.create_all(bind=engine)

    db_session = flask_scoped_session(session_factory, app)
    Base.query = db_session.query_property()
    return db_session
Beispiel #9
0
def create_app(config_name='development'):
    app = Flask(__name__)
    setup = config_dic.get(config_name)

    if setup:
        app.config.from_object(setup)

    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'],
                           convert_unicode=True)
    session_factory = sessionmaker(bind=engine,
                                   autocommit=False,
                                   autoflush=False)
    db_session = flask_scoped_session(session_factory)
    db_session.init_app(app)

    Base = declarative_base()
    Base.query = db_session.query_property()

    def do_setup():
        Base.metadata.create_all(bind=engine)

    do_setup()
    create_task_api(app)
    app.redis = Redis.from_url(app.config['REDIS_URL'])
    app.task_queue = rq.Queue('drweb-tasks', connection=app.redis)

    return {'app': app, 'db_session': db_session, 'Base': Base}
Beispiel #10
0
def initialize_database(autoinitialize=True):
    db_url = Configuration.database_url()
    if autoinitialize:
        SessionManager.initialize(db_url)
    session_factory = SessionManager.sessionmaker(db_url)
    _db = flask_scoped_session(session_factory, app)
    app._db = _db

    Configuration.load(_db)
    testing = 'TESTING' in os.environ
    log_level = LogConfiguration.initialize(_db, testing=testing)
    if app.debug is None:
        debug = log_level == 'DEBUG'
        app.debug = debug
    else:
        debug = app.debug
    app.config['DEBUG'] = debug
    _db.commit()
    app.log = logging.getLogger("Metadata web app")
    app.log.info("Application debug mode: %r", app.debug)
    for logger in logging.getLogger().handlers:
        app.log.info("Logs are going to %r", logger)

    # Register an error handler that logs exceptions through the
    # normal logging process and tries to turn them into Problem
    # Detail Documents.
    h = ErrorHandler(app, app.config['DEBUG'])

    @app.errorhandler(Exception)
    def exception_handler(exception):
        return h.handle(exception)
Beispiel #11
0
def setup_scoped_sessions(app: Flask, db_url: URL) -> Engine:
    engine = SQLAlchemyEngineManager.init_engine_for_postgres_instance(
        database_key=SQLAlchemyDatabaseKey.for_schema(SchemaType.CASE_TRIAGE),
        db_url=db_url,
    )
    session_factory = sessionmaker(bind=engine)
    app.scoped_session = flask_scoped_session(session_factory, app)
    return engine
def create_app(config):
    app = Flask(__name__, template_folder='app/templates')
    app.config.from_object(config)
    engine = create_engine(Config.SQLALCHEMY_DATABASE_URI)
    session_factory = sessionmaker(bind=engine)
    session = flask_scoped_session(session_factory, app)
    register_extensions(app)
    CORS(app)
    return app
Beispiel #13
0
    def __init__(self, engine, flask_app=None, timedelta_mins_from_utc=0):
        self.engine = engine
        self.timedelta_mins_from_utc = timedelta_mins_from_utc
        self.sessionmaker = sessionmaker(bind=self.engine)
        self.app = flask_app

        if flask_app:
            self.session = flask_scoped_session(self.sessionmaker, flask_app)
        else:
            self.session = scoped_session(self.sessionmaker)
Beispiel #14
0
def setup_db():
    global BASE
    engine = create_engine(f'sqlite:///{DBFILE}')
    BASE.metadata.bind = engine
    # Before doing this, clean up prev DB for testing purposes.
    # Submit to autograder WITHOUT this line.
    #BASE.metadata.drop_all(engine)
    # Create DB again.
    BASE.metadata.create_all(engine)
    DBSessionMaker = sessionmaker(bind=engine)
    return flask_scoped_session(DBSessionMaker, app)
Beispiel #15
0
def client(app, engine, tables):
    """
    Get a test client for your Flask app
    :param app: Test FlaskApp
    :param engine: sqlalchemy engine
    :param tables: creating all tables ## DON'T REMOVE FROM HERE
    :return: test client
    """
    session_factory = sessionmaker(bind=engine)
    app.db_session = flask_scoped_session(session_factory, app)
    with app.app_context():
        yield app.test_client()
Beispiel #16
0
def create_app():
    """ Create an app instance """
    app = Flask(__name__)
    app.config.from_object('config')
    app.json_encoder = JSONEncoder
    app.db_session = flask_scoped_session(session_factory, app)

    CORS(app)

    app.register_error_handler(Exception, handle_error)
    _ = list(map(app.register_blueprint, BLUEPRINTS))

    return app
Beispiel #17
0
def sync_transactions():
    ''' sync transactions from prev db '''
    click.echo('Init the db')
    from .base import OLD_DB_URL
    from sqlalchemy import create_engine
    from sqlalchemy.orm import scoped_session, sessionmaker
    __old_engine__ = create_engine(OLD_DB_URL)
    old_db_session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, bind=__old_engine__))
    old_db = flask_scoped_session(old_db_session, APP)
    result = old_db.execute("select * from transactions")
    results = {}
    for row in result:
        results[row['id']] = row
        _transaction = DB.query(Transaction).get(row['id'])
        if _transaction is None:
            # if row['transfer']:
            #     print('transfer. skipping for now')
            #     continue
            print("adding {}".format(row['id'], row))
            new_transaction = Transaction(record_id=row['id'],
                                          time=row['time'],
                                          account_id=row['account_id'],
                                          user_id=1,
                                          summ=row['sum'],
                                          income_id=row['income_id'],
                                          comments=row['comment'])
            print(new_transaction)
            DB.add(new_transaction)
            continue
        if _transaction.summ == row['sum'] and _transaction.account_id == row[
                'account_id'] and _transaction.transfer == row[
                    'transfer'] and _transaction.income_id == row[
                        'income_id'] and _transaction.comments == row[
                            'comment']:
            continue
        #print("{:3d} {:7.2f} {:3d} {:3d} {:3d} {:30s}".format(
        #    row['id'], row['sum'], row['account_id'], row['transfer'], row['income_id'], row['comment']
        #    ))

        print(row)
        print(_transaction)
        # \n    {:7s} {:3s} {:3s}
        # _transaction.summ,  _transaction.account_id, _transaction.transfer
    DB.commit()
    for _transaction in DB.query(Transaction).all():
        if _transaction.record_id in results:
            continue
        print(_transaction)
    old_db.close()
Beispiel #18
0
def app_sessions(app):
    app.url_map.strict_slashes = False
    app.db = SQLAlchemyDriver(config["DB"])
    # app.db = SQLAlchemyDriver('postgresql://*****:*****@postgres:5432/amanuensis_db')
    logger.warning("LUCA - DB connected")
    # TODO: we will make a more robust migration system external from the application
    #       initialization soon
    if config["ENABLE_DB_MIGRATION"]:
        logger.info("Running database migration...")
        migrate(app.db)
        logger.info("Done running database migration.")
    else:
        logger.info("NOT running database migration.")

    session = flask_scoped_session(app.db.Session, app)  # noqa
Beispiel #19
0
def app_sessions(app):
    app.url_map.strict_slashes = False
    app.db = SQLAlchemyDriver(config["DB"])

    # TODO: we will make a more robust migration system external from the application
    #       initialization soon
    if config["ENABLE_DB_MIGRATION"]:
        logger.info("Running database migration...")
        migrate(app.db)
        logger.info("Done running database migration.")
    else:
        logger.info("NOT running database migration.")

    session = flask_scoped_session(app.db.Session, app)  # noqa
    app.session_interface = UserSessionInterface()
Beispiel #20
0
def initialize_database(autoinitialize=True):
    testing = 'TESTING' in os.environ

    db_url = Configuration.database_url()
    if autoinitialize:
        SessionManager.initialize(db_url)
    session_factory = SessionManager.sessionmaker(db_url)
    _db = flask_scoped_session(session_factory, app)
    app._db = _db

    log_level = LogConfiguration.initialize(_db, testing=testing)
    debug = log_level == 'DEBUG'
    app.config['DEBUG'] = debug
    app.debug = debug
    _db.commit()
    logging.getLogger().info("Application debug mode==%r" % app.debug)
Beispiel #21
0
def get_db_session():
    if has_app_context():
        # This branch is used when we're working in the scope of Flask app
        global flask_db_session
        if not flask_db_session:
            from application import application
            flask_db_session = flask_scoped_session(get_session_factory(),
                                                    application)
        return flask_db_session
    else:
        # We use a different session if we're outside of Flask app,
        # for example running our code in a separate Thread
        global non_flask_db_session
        if not non_flask_db_session:
            non_flask_db_session = scoped_session(
                get_session_factory(DB_PREFIX))()
        return non_flask_db_session
Beispiel #22
0
def init(app, engine, session_factory):
    """Adds app.engine, and app.session_factory. Creates them if not passed in.

    :param app: flask app.
    :param engine: sqlalchemy engine.
    :param session_factory: session factory.
    """
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    # http://flask-sqlalchemy-session.readthedocs.io/en/v1.1/
    from flask_sqlalchemy_session import flask_scoped_session

    app.engine = (create_engine(app.config["SQLALCHEMY_DATABASE_URI"])
                  if engine is None else engine)
    app.session_factory = (sessionmaker(
        bind=app.engine) if session_factory is None else session_factory)
    app.scoped_session = flask_scoped_session(app.session_factory, app)
Beispiel #23
0
def create_app(Config):
    """
    Create Flask application using app factory pattern.

    :return: Flask app, SocketIO sockio
    """
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object(Config)
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    # initialize plugins
    from bfx_data_server.database import session_factory, User, Favourite
    dbSession = flask_scoped_session(session_factory, app)
    login_manager.init_app(app)
    sesh.init_app(app)
    sockio.init_app(app, manage_session=False)

    with app.app_context():
        from bfx_data_server.server.blueprints import home, auth, main, errors, data, api
        app.register_blueprint(home.home_bp)
        app.register_blueprint(auth.auth_bp, url_prefix='/auth')
        app.register_blueprint(main.main_bp)
        app.register_blueprint(errors.err, url_prefix='/error')
        app.register_blueprint(data.data_bp)
        app.register_blueprint(api.api_v1, url_perfix='/api_v1')

        @login_manager.user_loader
        def load_user(user_id):
            if user_id is not None:
                return dbSession.query(User).get(int(user_id))
            return None

        @app.shell_context_processor
        def make_shell_context():
            return {'db': dbSession, 'User': User, 'Favourite': Favourite}

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            dbSession.remove()

    return app, sockio
Beispiel #24
0
def create_app(dbsession: Session = None) -> Flask:
    """Create new Flask app

    :param dbsession: optional sqlalchemy Session, if `None`, a new one will be created.
    :return: Flask instance.
    """
    app = Flask(__name__)
    app.config.update()
    if not dbsession:
        # no session given, will setup an engine using DATABASE_URL env var, and create a session_factory from it
        database.setup()
        session_factory = sqlalchemy.orm.sessionmaker(bind=database.engine)
        database.session = flask_scoped_session(session_factory, app)
    else:
        # session given, this is for tests - session is setup in tests/conftest.py.
        database.setup(dbsession.bind.engine)
        database.session = dbsession

    # loads the routes
    init_app(app, database.session)

    return app
Beispiel #25
0
def app_sessions(app):
    app.url_map.strict_slashes = False
    app.db = SQLAlchemyDriver(app.config['DB'])
    migrate(app.db)
    session = flask_scoped_session(app.db.Session, app)  # noqa
    app.jinja_env.globals['csrf_token'] = generate_csrf_token
    app.storage_manager = StorageManager(
        app.config['STORAGE_CREDENTIALS'],
        logger=app.logger
    )
    enabled_idp_ids = (
        fence.settings
        .ENABLED_IDENTITY_PROVIDERS['providers']
        .keys()
    )
    # Add OIDC client for Google if configured.
    configured_google = (
        'OPENID_CONNECT' in app.config
        and 'google' in app.config['OPENID_CONNECT']
        and 'google' in enabled_idp_ids
    )
    if configured_google:
        app.google_client = GoogleClient(
            app.config['OPENID_CONNECT']['google'],
            HTTP_PROXY=app.config.get('HTTP_PROXY'),
            logger=app.logger
        )
    # Add OIDC client for multi-tenant fence if configured.
    configured_fence = (
        'OPENID_CONNECT' in app.config
        and 'fence' in app.config['OPENID_CONNECT']
        and 'fence' in enabled_idp_ids
    )
    if configured_fence:
        app.fence_client = OAuthClient(**app.config['OPENID_CONNECT']['fence'])
    app.session_interface = UserSessionInterface()
Beispiel #26
0
def test_constructor(sqlite_engine, flask_app):
    """Test init_app is called when an app is passed in the constructor"""
    with mock.patch.object(flask_scoped_session, "init_app"):
        ses = flask_scoped_session(sessionmaker(bind=sqlite_engine), flask_app)
        ses.init_app.assert_called_once_with(flask_app)
Beispiel #27
0
def unitialized_session(sqlite_engine):
    """Return a request_scoped_session that has not been used for a flask app"""
    ses = flask_scoped_session(sessionmaker(bind=sqlite_engine))
    _remove = ses.remove
    ses.remove = mock.Mock(side_effect=_remove)
    return ses
Beispiel #28
0
        ride_table_id = RideUsersTable(user_table_name=ride_request.created_by,
                                       ride_table_id=ride_id).write_to_db()
        return Response(j.dumps({"ride_id": ride_id}),
                        status=201,
                        mimetype='application/json')

    elif (action == "join_ride"):
        RideUsersTable(user_table_name=body["username"],
                       ride_table_id=body["ride_id"]).write_to_db()
        return Response(None, status=200, mimetype='application/json')

    elif (action == "delete_ride"):
        RideTable.read_from_db(body['ride_id']).delete_from_db()
        return Response(None, status=200, mimetype='application/json')


e = sql.create_engine("sqlite:///{}".format(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "riders.db")))
sf = orm.sessionmaker(bind=e)
session = fss.flask_scoped_session(sf, app)

Base.metadata.create_all(e, checkfirst=True)

if __name__ == "__main__":
    '''e = sql.create_engine("sqlite:///{}".format(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "riders.db")))
    Base.metadata.create_all(e, checkfirst=True)    
    sf = orm.sessionmaker(bind=e)
    session = fss.flask_scoped_session(sf, app)'''
    app.run(host='0.0.0.0', port=8080, debug=True)
Beispiel #29
0
 def init(cls, app: Flask) -> None:
     cls.session = flask_scoped_session(session_factory, app)
Beispiel #30
0
        return JSONEncoder.default(self, o)

app = Flask(__name__)
app.json_encoder = JsonEncoder

@app.route("/")
def index():
    return "Hello! v2"

@app.route("/environ")
def environ():
    return ppr(os.environ)

DB_URL = os.environ["DB_URL"]#, "postgres://docker@db:5432/docker")
engine = create_engine(DB_URL)
session = flask_scoped_session(sessionmaker(engine), app)

@app.route("/sql/<query>")
def sql(query):
    response = {"query": query}
    try:
        query_result = session.execute(query)
        session.commit()
        response["message"] = "Executed successfully."
        if query_result.rowcount is not None:
            response["rows_affected"] = query_result.rowcount
        if query_result.returns_rows:
            response["returned_rows"] = query_result.fetchall()
    except Exception as ex:
        response["error"] = str(ex)
        response["traceback"] = format_exc()
Beispiel #31
0
   }
)

# mail setup
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'

mail = Mail(app)

app.secret_key = 'bdfa8a83f16eb4f95dc2473fe4a50820b14e74cc70cef6ae'
# print(os.random(24))
sess = flask_scoped_session(session_factory, app)

########## CAS AUTHENTICATION ###########
cas = CAS(app)
app.config['CAS_SERVER'] = "https://fed.princeton.edu/cas/login"
app.config['CAS_AFTER_LOGIN'] = '******'
app.config['CAS_AFTER_LOGOUT'] = 'http://princeton-qroom.herokuapp.com/caslogout'
# app.config['CAS_AFTER_LOGOUT'] = 'http://*****:*****@app.route('/')
def index():
   if isLoggedIn():
      return redirect(url_for('booking'))
      session['admin'] = True
def test_constructor(sqlite_engine, flask_app):
    """Test init_app is called when an app is passed in the constructor"""
    with mock.patch.object(flask_scoped_session, "init_app"):
        ses = flask_scoped_session(sessionmaker(bind=sqlite_engine), flask_app)
        ses.init_app.assert_called_once_with(flask_app)
Beispiel #33
0
Base.prepare(engine, reflect=True)

# TODO make base classes use the correct engine
# Currently, this uses sqlite o.O: `num_authors = Author.query.count()`
Author = Base.classes.authors
Document = Base.classes.documents
Label = Base.classes.labels

toolbar = DebugToolbarExtension(app)

# Enable SQLAlchemy in Debug Toolbar without flask-sqlalchemy :)
from flask.ext.sqlalchemy import _EngineDebuggingSignalEvents
_EngineDebuggingSignalEvents(engine, app.import_name).register()

session_factory = sessionmaker(bind=engine)
session = flask_scoped_session(session_factory, app)

# From http://flask.pocoo.org/snippets/33/
@app.template_filter()
def friendly_time(dt, past_="ago",
    future_="from now",
    default="just now"):
    """
    Returns string representing "time since"
    or "time until" e.g.
    3 days ago, 5 hours from now etc.
    """

    now = datetime.now()
    if now > dt:
        diff = now - dt
Beispiel #34
0
# set up Flask
app = Flask(__name__, static_url_path='')
app.secret_key = conf.get("server", "secret")
app.config['UPLOAD_FOLDER'] = "/tmp"

start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


# set up database connection
db_url = conf.get("database", "url")
engine = create_engine(db_url, pool_recycle=3600)

# flask-mysqlalchemy integration
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = flask_scoped_session(DBSession, app) # type: Session


# set up Jinja rendering environment for Latex
# http://flask.pocoo.org/snippets/55/
texenv = app.create_jinja_environment()
# texenv.block_start_string = '((*'
# texenv.block_end_string = '*))'
texenv.variable_start_string = '((('
texenv.variable_end_string = ')))'
# texenv.comment_start_string = '((='
# texenv.comment_end_string = '=))'


# format float as EUR value
@app.template_filter()
Beispiel #35
0
def create_app(verbosity=None):
    """Creates a Flask application object that registers all the blueprints on
    which the actual routes are defined.

    Parameters
    ----------
    verbosity: int, optional
        logging verbosity to override the
        :attr:`logging_verbosity <tmserver.config.ServerConfig.logging_verbosity>`
        setting in the configuration file (default: ``None``)

    Returns
    -------
    flask.Flask
        Flask application

    """
    log_formatter = logging.Formatter(
        fmt='%(process)5d/%(threadName)-12s| %(levelname)-8s| %(message)s [[%(name)s @ %(pathname)s:%(lineno)d]]',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    log_handler = logging.StreamHandler(stream=sys.stdout)
    log_handler.setFormatter(log_formatter)
    if verbosity is None:
        verbosity = cfg.logging_verbosity
    log_level = map_logging_verbosity(verbosity)

    app = Flask('wsgi')
    app.config['PROPAGATE_EXCEPTIONS'] = True

    app.logger.handlers = []  # remove standard handlers
    app.logger.setLevel(log_level)
    app.logger.addHandler(log_handler)

    tmserver_logger = logging.getLogger('tmserver')
    tmserver_logger.setLevel(log_level)
    tmserver_logger.addHandler(log_handler)

    tmlib_logger = logging.getLogger('tmlib')
    tmlib_logger.setLevel(log_level)
    tmlib_logger.addHandler(log_handler)

    flask_jwt_logger = logging.getLogger('flask_jwt')
    flask_jwt_logger.setLevel(log_level)
    flask_jwt_logger.addHandler(log_handler)

    gevent_logger = logging.getLogger('gevent')
    gevent_logger.addHandler(log_handler)
    gc3pie_logger = logging.getLogger('gc3.gc3libs')
    gc3pie_logger.addHandler(log_handler)
    sqlalchemy_logger = logging.getLogger('sqlalchemy.engine')
    sqlalchemy_logger.addHandler(log_handler)
    wsgi_logger = logging.getLogger('wsgi')
    wsgi_logger.addHandler(log_handler)
    if verbosity > 4:
        gevent_logger.setLevel(logging.DEBUG)
        gc3pie_logger.setLevel(logging.DEBUG)
        sqlalchemy_logger.setLevel(logging.DEBUG)
        wsgi_logger.setLevel(logging.DEBUG)
    elif verbosity > 3:
        gevent_logger.setLevel(logging.INFO)
        gc3pie_logger.setLevel(logging.INFO)
        sqlalchemy_logger.setLevel(logging.INFO)
        wsgi_logger.setLevel(logging.INFO)
    else:
        gevent_logger.setLevel(logging.ERROR)
        gc3pie_logger.setLevel(logging.ERROR)
        sqlalchemy_logger.setLevel(logging.ERROR)
        wsgi_logger.setLevel(logging.ERROR)

    app.json_encoder = TmJSONEncoder

    if cfg.secret_key == 'default_secret_key':
        app.logger.warn('The application will run with the default secret key!')
    elif not cfg.secret_key:
        app.logger.critical('Specify a secret key for this application!')
        sys.exit(1)
    app.config['SECRET_KEY'] = cfg.secret_key

    app.config['JWT_EXPIRATION_DELTA'] = cfg.jwt_expiration_delta

    ## Error handling

    # Register custom error classes
    register_http_error_classes(app)

    # Register SQLAlchemy error classes
    @app.errorhandler(NoResultFound)
    def _handle_no_result_found(error):
        response = jsonify(error={
            'message': error.message,
            'status_code': 400,
            'type': error.__class__.__name__
        })
        logger.error('no result found: ' + error.message)
        response.status_code = 400
        return response

    @app.errorhandler(MultipleResultsFound)
    def _multiple_results_found(error):
        response = jsonify(error={
            'message': error.message,
            'status_code': 409,
            'type': error.__class__.__name__
        })
        logger.error('multiple results found: ' + error.message)
        response.status_code = 409
        return response

    @app.errorhandler(IntegrityError)
    def _handle_integrity_error(error):
        response = jsonify(error={
            'error': True,
            'message': error.message,
            'status_code': 500,
            'type': error.__class__.__name__
        })
        logger.error('database integrity error: ' + error.message)
        response.status_code = 500
        return response


    ## Initialize Plugins
    jwt.init_app(app)

    # Create a session scope for interacting with the main database
    engine = create_db_engine(cfg.db_master_uri)
    create_db_tables(engine)
    session_factory = create_db_session_factory()
    session_factory.configure(bind=engine)
    session = flask_scoped_session(session_factory, app)

    from tmserver.extensions import gc3pie
    gc3pie.init_app(app)

    ## Import and register blueprints
    from tmserver.api import api
    app.register_blueprint(api, url_prefix='/api')

    from tmserver.jtui import jtui
    app.register_blueprint(jtui, url_prefix='/jtui')

    # For uWSGI fork()
    engine.dispose()

    return app
Beispiel #36
0
from .oauth import GOOGLE, REDIRECT_URI, get_user_info
from .database import User, \
    Account, \
    DBJsonEncoder, Income, Interval
from .currencies import UserCurrencies, Currency
from .currencies import usercurrency_delete, usercurrency_put, currency_get  # pylint: disable=W0611
from .base import DB_URL, DB_SESSION
from .utils import strip_numbers
from .transactions import Transaction, transaction_get, transaction_put, transaction_post, transaction_delete  # pylint: disable=W0611
#  from .payforward import Payforward

__version__ = "1.0.1"

APP = Flask(__name__)  # create the application instance :)
APP.config.from_object(__name__)  # load config from this file , flaskr.py
DB = flask_scoped_session(DB_SESSION, APP)
SECRET = 'icDauKnydnomWovijOakgewvIgyivfahudWocnelkikAndeezCogneftyeljogdy'

# Load default config and override config from an environment variable
APP.config.update(
    dict(SECRET_KEY=SECRET,
         PREFERRED_URL_SCHEME='http',
         SESSION_TYPE='sqlalchemy',
         SQLALCHEMY_DATABASE_URI=DB_URL,
         SQLALCHEMY_TRACK_MODIFICATIONS=False,
         DEBUG=True))

APP.config.from_envvar('E4_SETTINGS', silent=True)


@APP.teardown_appcontext
def unitialized_session(sqlite_engine):
    """Return a request_scoped_session that has not been used for a flask app"""
    ses = flask_scoped_session(sessionmaker(bind=sqlite_engine))
    _remove = ses.remove
    ses.remove = mock.Mock(side_effect=_remove)
    return ses