Example #1
0
def register_extensions(app):

    api.app = app

    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)

    api.init_app(app)
    if app.config['ELASTIC_ENABLED'] == '1':
        apm.init_app(app)
        logging.getLogger('elasticapm').setLevel(30)
    else:
        app.logger.info(
            'ELASTIC_ENABLED: FALSE, set ELASTIC_ENABLED=1 to enable')

    try:
        jwt.init_app(app)
    except Exception as error:
        app.logger.error("Failed to initialize JWT library: " + str(error))

    cache.init_app(app)
    db.init_app(app)
    CORS(app)

    # Set up Marshmallow
    with app.app_context():
        setup_marshmallow()
Example #2
0
def register_extensions(app):
    origins = app.config.get('CORS_ORIGIN_WHITELIST', '*')
    cors.init_app(app, origins=origins)
    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    jwt.init_app(app)
Example #3
0
def create_app(config=None):
    app = JSONFlask(__name__)
    if config:
        app.config.from_object(config)

    db.init_app(app)
    jwt.init_app(app)
    cors.init_app(app)
    mail.init_app(app)

    app.register_blueprint(account_bp, url_prefix='/api/v1/account')
    app.register_blueprint(categories_bp, url_prefix='/api/v1/categories')
    app.register_blueprint(food_item_state_bp,
                           url_prefix='/api/v1/food_item_state')
    app.register_blueprint(stock_bp, url_prefix='/api/v1/stock')
    app.register_blueprint(snapshot_bp, url_prefix='/api/v1/snapshot')
    app.register_blueprint(unit_of_measure_bp,
                           url_prefix='/api/v1/unit_of_measure')

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        return app.send_static_file("index.html")

    return app
Example #4
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
Example #5
0
def register_extensions(app):
    """
    Init extension
    :param app:
    :return:
    """
    client.app = app
    client.init_app(app)
    celery.init_app(app)
    jwt.init_app(app)
    if os.environ.get('FLASK_DEBUG') == '0':
        # logger
        logger = logging.getLogger('api')
        logger.setLevel(logging.ERROR)
        logger.addHandler(app_log_handler)

        @app.after_request
        def after_request(response):
            # This IF avoids the duplication of registry in the log,
            # since that 500 is already logged via @app.errorhandler.
            if response.status_code != 500:
                ts = strftime('[%Y-%b-%d %H:%M]')
                logger.error('%s %s %s %s %s %s', ts, request.remote_addr,
                             request.method, request.scheme, request.full_path,
                             response.status)
            return response

        @app.errorhandler(Exception)
        def exceptions(e):
            ts = strftime('[%Y-%b-%d %H:%M]')
            tb = traceback.format_exc()
            logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR\n%s', ts,
                         request.remote_addr, request.method, request.scheme,
                         request.full_path, tb)
            return "Internal Server Error", 500
Example #6
0
def init_extensions(app):
    if app.config["REPOSITORY"] == "MYSQL":
        db.init_app(app)

    cors.init_app(app)
    ma.init_app(app)
    jwt.init_app(app)
Example #7
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    cache.init_app(app)
    db.init_app(app)
    jwt.init_app(app)
    apm.init_app(app) if app.config['ELASTIC_ENABLED'] == '1' else None
    sched.init_app(app)

    CORS(app)
    Compress(app)

    if app.config.get('ENVIRONMENT_NAME') in ['test', 'prod']:
        if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == 'true':
            sched.start()
            _schedule_NRIS_jobs(app)
            # This is here to prevent this from running in production until we are confident in the permit data.
            if app.config.get('ENVIRONMENT_NAME') == 'test':
                _schedule_ETL_jobs(app)

    return None
Example #8
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    if app.config['ELASTIC_ENABLED'] == '1':
        apm.init_app(app)
    else:
        app.logger.debug(
            'ELASTIC_ENABLED: FALSE, set ELASTIC_ENABLED=1 to enable')

    try:
        jwt.init_app(app)
    except Exception as error:
        app.logger.error("Failed to initialize JWT library: " + str(error))

    cache.init_app(app)
    db.init_app(app)

    CORS(app)
    Compress(app)

    return None
Example #9
0
def configure_extensions(app, cli):
    """configure flask extensions
    """
    db.init_app(app)
    jwt.init_app(app)

    if cli is True:
        migrate.init_app(app, db)
Example #10
0
def register_extensions(app):
    db.init_app(app)
    ma.init_app(app)
    bcrypt.init_app(app)
    jwt.init_app(app)
    initialize_routes(api)
    api.init_app(app)
    return None
Example #11
0
def create_app(script_info=None):
    """Application factory."""
    # instantiate the app
    app = Flask(__name__)

    # enable cors
    CORS(app)

    # set config
    app_settings = os.getenv("APP_SETTINGS")
    app.config.from_object(app_settings)

    # set up extensions
    db.init_app(app)
    bcrypt.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    graphql_client.init_app(app)

    if app.config["TESTING"]:
        redis_store = FlaskRedis.from_custom_provider(FakeStrictRedis)
    else:
        redis_store = redis_client
    redis_store.init_app(app)

    # register blueprints
    from app.api.rest.users import users_blueprint
    app.register_blueprint(users_blueprint)
    from app.api.rest.topics import topics_blueprint
    app.register_blueprint(topics_blueprint)
    from app.api.rest.messages import messages_blueprint
    app.register_blueprint(messages_blueprint)

    if app.debug:

        @app.route("/graphql", methods=["GET"])
        def gql_playground():
            """User interface for writing graphql queries."""
            return PLAYGROUND_HTML, 200

    # shell context for flask cli
    @app.shell_context_processor
    def ctx():
        return {
            "app": app,
            "db": db,
            "User": User,
            "Topic": Topic,
            "Message": Message,
            "redis_store": redis_store
        }

    @app.before_first_request
    def create_tables():
        """Create all tables in the database, if not existing."""
        db.create_all()

    return app
Example #12
0
def init_extensions(app):
    db.init_app(app)
    cors.init_app(app, resources={
        r"/*": {
            "origins": "*"
        },
    })
    jwt.init_app(app)
    ma.init_app(app)
Example #13
0
def register_extensions(flask_app):
    from app.extensions import cors, jwt, mongoengine, validator, swagger

    cors.init_app(flask_app)
    jwt.init_app(flask_app)
    mongoengine.init_app(flask_app)
    validator.init_app(flask_app)
    swagger.template = flask_app.config['SWAGGER_TEMPLATE']
    swagger.init_app(flask_app)
Example #14
0
def register_extensions(app, db):
    """Register Flask extensions."""
    # cache.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    login_manager.init_app(app)
    bcrypt.init_app(app)
    ma.init_app(app)
Example #15
0
def _init_extensions(app):
    celery.init_app(app)

    class ContextQueueOnce(QueueOnce):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return super(ContextQueueOnce, self).__call__(*args, **kwargs)
    celery.QueueOnce = ContextQueueOnce
    db.init_app(app)
    jwt.init_app(app)
Example #16
0
def register_extensions(app):
    api.app = app
    api.init_app(app)

    db.init_app(app)
    jwt.init_app(app)

    CORS(app)
    Compress(app)

    return None
Example #17
0
def register_extensions(app, config_object):
    """Init extension. You can see list extension in the extensions.py

    Args:
        app: Flask handler application
        config_object: settings of the application
    """
    # Order matters: Initialize SQLAlchemy before Marshmallow
    # create log folder
    db.app = app
    jwt.init_app(app)
    db.init_app(app)

    @app.after_request
    def after_request(response):
        # This IF avoids the duplication of registry in the log,
        # since that 500 is already logged via @app.errorhandler.
        if response.status_code != 500:
            ts = strftime('[%Y-%b-%d %H:%M]')
            logger.info('%s %s %s %s %s %s', ts, request.remote_addr,
                        request.method, request.scheme, request.full_path,
                        response.status)

        return response

    @app.errorhandler(Exception)
    def exceptions(e):
        ts = strftime('[%Y-%b-%d %H:%M]')
        tb = traceback.format_exc()
        error = '{} {} {} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format(
            ts, request.remote_addr, request.method, request.scheme,
            request.full_path, tb, str(e))

        logger.error(error)
        logger_auth.error(error)
        return send_error(message='INTERNAL SERVER ERROR', code=500)

    @parser.error_handler
    def handle_error(error, req, schema, *, error_status_code, error_headers):
        return send_error(
            message='Parser error. Please check your requests body',
            code=error_status_code)

    # Return validation errors as JSON
    @app.errorhandler(422)
    @app.errorhandler(400)
    def handle_error(err):
        headers = err.data.get("headers", None)
        messages = err.data.get("messages", ["Invalid request."])
        if headers:
            return jsonify({"errors": messages}), err.code, headers
        else:
            return jsonify({"errors": messages}), err.code
Example #18
0
def init_extensions(app):
    if app.config['REPO_ENGINE'] == 'MYSQL':
        db.init_app(app)

    cors.init_app(app, resources={
        r"/*": {
            "origins": "*"
        },
    })
    jwt.init_app(app)
    ma.init_app(app)
    mail.init_app(app)
Example #19
0
def register_extensions(app):

    debug_toolbar.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    mail.init_app(app)
    api.init_app(app)
    jwt.init_app(app)
    limiter.init_app(app)
Example #20
0
def extensions(app):
    """
    Add 0 or more extensions to the flask application.
    Mutates the app passed in.

    :param app: Flask application instance
    :return: None
    """
    jwt.init_app(app)
    db.init_app(app)
    ma.init_app(app)

    return None
Example #21
0
def register_extensions(app):
    """
    Register 0 or more extensions (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    initialize_db(app)
    ma.init_app(app)
    jwt.init_app(app)
    cors.init_app(app)

    return None
Example #22
0
def register_extensions(app):
    """Init extension. You can see list extension in the extensions.py

    Args:
        app: Flask handler application
    """
    # Order matters: Initialize SQLAlchemy before Marshmallow
    db.init_app(app)
    ma.init_app(app)
    jwt.init_app(app)
    login_manager.init_app(app)
    # logger
    logger = logging.getLogger('api')
    logger.setLevel(logging.INFO)
    logger.addHandler(app_log_handler)

    @app.after_request
    def after_request(response):
        # This IF avoids the duplication of registry in the log,
        # since that 500 is already logged via @app.errorhandler.
        if response.status_code != 500:
            ts = strftime('[%Y-%b-%d %H:%M]')
            logger.error('%s %s %s %s %s %s',
                         ts,
                         request.remote_addr,
                         request.method,
                         request.scheme,
                         request.full_path,
                         response.status)
        return response

    @app.errorhandler(Exception)
    def exceptions(e):
        ts = strftime('[%Y-%b-%d %H:%M]')
        tb = traceback.format_exc()
        error = '{} {} {} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format \
            (
                ts,
                request.remote_addr,
                request.method,
                request.scheme,
                request.full_path,
                tb,
                str(e)
            )

        logger.error(error)

        return send_error(message='INTERNAL SERVER ERROR', code=500)
Example #23
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.static_url_path = f'{Config.BASE_PATH}/swaggerui'
    api.init_app(app)

    cache.init_app(app)
    db.init_app(app)
    jwt.init_app(app)
    migrate.init_app(app, db)

    CORS(app)

    return None
Example #24
0
def register_extensions(app):
    db.init_app(app)

    # import redis lua scripts
    scripts = ["replaceOrInsertUser", "appendMediasToStory", "replaceOrInsertStory"]
    for script in scripts:
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), script+".lua"), "r") as lua:
            setattr(db, script, db.register_script(lua.read()))

    jwt.init_app(app)

    @jwt.token_in_blacklist_loader
    def check_if_token_is_invalid(decrypted_token):
        jti = decrypted_token['jti']
        entry = db.get("z:tokens:{jti}".format(jti=jti))
        return True if entry is None else entry == "true"
Example #25
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    jwt.init_app(app)

    # rotas implementadas
    app.register_blueprint(carrinho_api)
    app.register_blueprint(usuario_api)
    app.register_blueprint(endereco_api)
    app.register_blueprint(produto_compra_api)

    return app
Example #26
0
def register_extensions(app, content, config_object):
    """
    Init extension
    :param app:
    :param content:
    :return:
    """
    client.app = app
    client.init_app(app)
    socketio.init_app(app)
    # don't start extensions if content != app
    if content == 'app':
        jwt.init_app(app)
    # logger
    logger = logging.getLogger('api')
    logger.setLevel(logging.ERROR)
    logger.addHandler(app_log_handler)

    @app.after_request
    def after_request(response):
        # This IF avoids the duplication of registry in the log,
        # since that 500 is already logged via @app.errorhandler.
        if response.status_code != 500:
            ts = strftime('[%Y-%b-%d %H:%M]')
            logger.error('%s %s %s %s %s %s', ts, request.remote_addr,
                         request.method, request.scheme, request.full_path,
                         response.status)
        return response

    @app.errorhandler(Exception)
    def exceptions(e):
        ts = strftime('[%Y-%b-%d %H:%M]')
        tb = traceback.format_exc()
        error = '{} {} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format \
                (
                ts,
                request.remote_addr,
                request.method,
                request.scheme,
                request.full_path,
                tb
            )

        logger.error(error)

        return "Internal Server Error", 500
Example #27
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    cache.init_app(app)
    db.init_app(app)
    jwt.init_app(app)
    apm.init_app(app) if app.config['ELASTIC_ENABLED'] == '1' else None
    sched.init_app(app)

    CORS(app)
    Compress(app)

    return None
Example #28
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    try:
        jwt.init_app(app)
    except Exception as error:
        app.logger.error("Failed to initialize JWT library: " + str(error))

    cache.init_app(app)
    db.init_app(app)

    CORS(app)

    return None
Example #29
0
def create_app(config_filename):
    '''create an instance of the Flask application'''
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('config.BaseConfig')
    app.config.from_pyfile('config.py')

    # Register db with the app
    from app import db
    db.init_app(app)

    #Register the jwt extension instance with the app
    from app.extensions import jwt
    jwt.init_app(app)

    #Register the api blueprint with app
    from .api.v1 import version1
    app.register_blueprint(version1)

    return app
Example #30
0
def create_app():
    app = Flask(__name__)
    api = Api(app)
    jwt.init_app(app)
    app.config.from_object(Config)
    db.init_app(app)
    ma.init_app(app)

    api.add_resource(UserRegister, '/register')
    api.add_resource(User, '/user/<int:user_id>')
    api.add_resource(UserLogin, '/login')
    # api.add_resource(GithubLogin, '/login/github')
    api.add_resource(SetPassword, '/user/password')
    api.add_resource(OauthResource, '/login/<provider_name>')
    api.add_resource(GithubAuthorize, '/login/github/authorized', endpoint='github.authorize')

    oauth.init_app(app)

    return app
Example #31
0
def create_app(config=None):
    
    app = Flask(__name__)

    if config:
        app.config.from_object(config)
    else:
        app.config.from_object(os.environ['APP_SETTINGS'])

    # Init logger
    handler = RotatingFileHandler(app.config['LOGGING_LOCATION'], maxBytes=10000, backupCount=1)
    handler.setLevel(app.config['LOGGING_LEVEL'])
    app.logger.addHandler(handler)

    # Init routes
    from app.home.views import home
    app.register_blueprint(home)

    from app.home.api import TestApi
    api.add_resource(TestApi, '/api/protected')

    from app.user.api import UserApi
    api.add_resource(UserApi, '/api/user/register')

    # Init extensions
    db.init_app(app)
    api.init_app(app)
    bcrypt.init_app(app)

    from app.user.auth import authenticate, identity, payload_handler
    jwt.authentication_handler(authenticate)
    jwt.identity_handler(identity)
    jwt.jwt_payload_handler(payload_handler)
    jwt.init_app(app)

    return app