예제 #1
0
def create_app(config):
    # Application factory

    app = Flask(__name__)
    register_blueprints(app)
    register_metrics(app,
                     app_version=config["version"],
                     app_config=config["config"])
    return app
예제 #2
0
def create_app(config: BaseConfig) -> Flask:
    """
    Creates and returns a Flask application object configured

    :param config: A config object usable by Flask's 'app.config.from_object()' function.
    :type config: object
    :return: The Flask application object
    :rtype: Flask
    """
    app = Flask(config.SERVICE_NAME)
    app.config.from_object(config)

    # Configure Redis client
    if app.testing:
        redis_store = FlaskRedis.from_custom_provider(FakeRedis())
    else:
        redis_store = FlaskRedis()
    redis_store.init_app(app)
    app.redis = redis_store

    logger = getLogger("werkzeug")
    logger.addFilter(HealthLogFilter())

    api_blueprint = Blueprint(config.SERVICE_NAME, __name__)
    health_blueprint = Blueprint("healthcheck", __name__)

    api = Api(
        api_blueprint,
        title=f"{config.SERVICE_LONG_NAME} API",
        version=f"{config.API_VERSION}",
        description=config.SERVICE_DESCRIPTION,
    )

    # Add Keyvalue store api namespace
    api.add_namespace(keyvaluestore_api, path="")

    # Add endpoints for prometheus_client
    register_metrics(app, app_version="0.0.1", app_config="production")

    healthcheck = Api(
        health_blueprint,
        title="Healthcheck Endpoint",
        version="1",
        description=
        f"An API returning health information for the {config.SERVICE_NAME} service.",
    )
    healthcheck.add_namespace(healthcheck_api, path="")

    app.register_blueprint(api_blueprint, url_prefix="/api")
    app.register_blueprint(health_blueprint, url_prefix="/health")

    return app, redis_store
def initialize_consul_client(app):
    server_port = app.config['SERVER_PORT']

    app_name = app.config['APP_NAME']

    profile = app.config['SPRING_PROFILES_ACTIVE']

    hostname = app.config['HOSTNAME']

    # Consul
    # This extension should be the first one if enabled:
    consul = Consul(app=app)
    # Fetch the configuration:
    consul.apply_remote_config(namespace=f'config/application,{profile}/data')
    # Register Consul service:
    consul.register_service(name=app_name,
                            interval='30s',
                            tags=[app_name],
                            port=server_port,
                            httpcheck=hostname + ":" + str(server_port) +
                            "/actuator/health")

    if profile != 'prod':
        jwt_secret = ""
        for data in yaml.load_all(app.config[''], Loader=yaml.BaseLoader):
            try:
                jwt_secret = data['com']['microservice']['authentication'][
                    'jwt']['keyValue']
                break
            except Exception:
                log.warning("Not found jwt_secret")

        if jwt_secret == "":
            raise Exception("jwt_secret not found")
        log.debug('Jwt Secret: %s', jwt_secret)
        app.config['JWT_SECRET_KEY'] = jwt_secret

    else:
        app.config['JWT_PUBLIC_KEY'] = open(app.config['JWT_PUBLIC_KEY'],
                                            "r").read()

    log.debug('Config environment: %s', app.config)

    # provide app's version and deploy environment/config name to set a gauge metric
    register_metrics(app, app_version="v0.1.2", app_config="staging")
def initialize_spring_cloud_client(app):
    server_port = app.config['SERVER_PORT']

    # The following code will register server to eureka server and also start to send heartbeat every 30 seconds
    eureka_client.init(eureka_server=app.config['EUREKA_SERVER'],
                       app_name="python-service",
                       instance_port=server_port)

    address = app.config["SPRING_CLOUD_CONFIG_URI"]

    profile = app.config['SPRING_PROFILES_ACTIVE']

    app_name = app.config['APP_NAME']

    config_client = spring.ConfigClient(
        app_name=app_name,
        url="{address}/{app_name}/{profile}.json",
        profile=profile,
        branch=None,
        address=address)
    config_client.url = config_client.url[:-5]
    config_client.get_config(
        headers={'X-Encrypt-Key': app.config['X_ENCRYPT_KEY']})

    if profile != 'prod':
        try:
            jwt_secret = config_client.config['propertySources'][0]['source'][
                'security.oauth2.resource.jwt.keyValue']
        except Exception:
            jwt_secret = config_client.config['propertySources'][1]['source'][
                'security.oauth2.resource.jwt.keyValue']
        log.debug('Jwt Secret: %s', jwt_secret)
        app.config['JWT_SECRET_KEY'] = base64.b64decode(jwt_secret)
        app.config['SECRET_KEY'] = app.config['JWT_SECRET_KEY']

    else:
        app.config['JWT_PUBLIC_KEY'] = open(app.config['JWT_PUBLIC_KEY'],
                                            "r").read()

    log.debug('Config environment: %s', app.config)

    # provide app's version and deploy environment/config name to set a gauge metric
    register_metrics(app, app_version="v0.1.2", app_config="staging")
예제 #5
0
def create_metrics(app):
    app_mode = os.getenv("FLASK_ENV")
    register_metrics(app, app_version="v1.4.151", app_config=app_mode)
    dispatcher = DispatcherMiddleware(app.wsgi_app,
                                      {"/metrics": make_wsgi_app()})
    return dispatcher
    if conn.ping(True):
        print("connected to mysql db")
    mycursor = conn.cursor()

    print("inside recipe_needed")
    # Getting input as an argument from user
    param = request.args
    recipe = param.get('recipe_name')
    print(recipe)
    # SQL query
    query = f"""select * from recipe_box where recipe_name ='{recipe}'"""
    mycursor.execute(query)
    recs = mycursor.fetchall()
    conn.close()
    # Closing db connection

    ## Showing the data
    for rec in recs:
        print(rec)
    return jsonify(recs)


# provide app's version and deploy environment/config name to set a gauge metric
register_metrics(app, app_version="v0.1.2", app_config="staging")

# Plug metrics WSGI app to your main app with dispatcher
dispatcher = DispatcherMiddleware(
    app.wsgi_app, {"/recipe_box/recipes/metrics": make_wsgi_app()})

# hostname and port number
run_simple(hostname="0.0.0.0", port=7010, application=dispatcher)
예제 #7
0
from flask import Flask
from prometheus_client import make_wsgi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
from flask_prometheus_metrics import register_metrics

app = Flask(__name__)


@app.route("/")
def index():
    return "Hello metrics! Go to /metrics"


register_metrics(app, app_version="v0.1.2", app_config="production")

dispatcher = DispatcherMiddleware(app.wsgi_app, {"/metrics": make_wsgi_app()})

run_simple(hostname="0.0.0.0", port=5000, application=dispatcher)
# Prometheus exporter
from prometheus_client import make_wsgi_app
from flask_prometheus_metrics import register_metrics

# Werkzeug
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

apm = ElasticAPM(
    app,
    server_url=app.config['APM_URL'],
    service_name='crawler',
    secret_token='d910fe18cd0fde99ee282685cc7046e14a8491df474b85c8',
    logging=False)

from app import routes, models
# Prometheus metrics
# Definindo versão da app e environment
register_metrics(app, app_version="v0.1.2", app_config="local")
# WSGI de métricas no app
dispatcher = DispatcherMiddleware(app.wsgi_app, {"/metrics": make_wsgi_app()})

if __name__ == '__main__':
    # app.run(debug=True)
    run_simple(hostname="0.0.0.0", port=5000, application=dispatcher)
예제 #9
0
        return render_template('podinfo.html',
                               page_title="Dev Quotes - Container info",
                               os_info=get_system_info())

    @app.route('/about', methods=['GET'])
    def about():
        return render_template('about.html', page_title="Dev Quotes - About")

    @app.route('/healthz', methods=['GET'])
    def health():
        """
        Fake liveness probe
        """
        return 'OK'

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    return app


app = create_app()
register_metrics(app, app_version="v0.2", app_config="dev")
dispatcher = DispatcherMiddleware(app.wsgi_app, {"/metrics": make_wsgi_app()})

if __name__ == "__main__":
    run_simple("0.0.0.0", 8080, application=dispatcher)
예제 #10
0
def create_app(app_name, config={}):
    """
    App Factory Tools

    Workflow: follow the track_infos,current has 15 steps.

    primary workflow:

    1. call a dirty way to hack depends package,e.g: webargs
    1. merge config from env.FANTASY_SETTINGS_MODULE if user defined
    1. call error_handle if user defined
    1. call run_admin if user defined
    1. call run_cli if user defined
    :return:
    """

    track_info('(00/08)fantasy track mode active...')
    from . import error_handler, cli
    logging_level = 'INFO' if os.environ.get('FLASK_ENV',
                                             'dev') == 'dev' else 'ERROR'
    logging_level = 'DEBUG' if os.environ.get('FLASK_DEBUG') else logging_level

    if os.environ.get('FANTASY_ACTIVE_LOGGING', 'no') == 'yes':
        track_info(f'        logging mode:{logging_level}')
        init_logging(logging_level)

    track_info('(01/08)i18n webargs...')
    if os.environ.get('LANG') == 'zh_CN.UTF-8':
        from .i18n import zh_cn
        zh_cn()
        pass

    track_info('(02/08)initial app...')
    mod = importlib.import_module(app_name)
    app = FantasyFlask(app_name, root_path=os.path.dirname(mod.__file__))
    app.root_app = os.environ.get('FANTASY_APP', app_name)
    app.logger.info("logger active")

    track_info('(03/08)update app.config...')
    if config:
        app.config.update(config)

    app.config.update(PROPAGATE_EXCEPTIONS=False)
    app.log_exception = functools.partial(
        ff_log_exception, original_log_exception=app.log_exception)
    # 由外部做显式声明,否则不做调用
    config_module = os.environ.get('FANTASY_SETTINGS_MODULE', None)
    if config_module:
        track_info("       found config module %s,try load it..." %
                   config_module)
        app.config.from_object(config_module)

    track_info("       merge config from os.environment.")
    for k in config_env_list:
        if not app.config.get(k):
            track_info("              key: %s merged" % k)
            app.config.update({k: os.environ.get(k, None)})
            pass
        pass

    track_info("       initial SQL database when active.")
    if app.db:
        if app.config['FANTASY_AUTO_MIGRATE'] == 'yes':
            smart_database(app)
        app.db.init_app(app)

    track_info("       initial Doc database when active.")
    if app.doc_db:
        mongodb_kwargs = {
            k.upper(): v
            for (k, v) in app.config.items()
            if k.upper().startswith('MONGODB_')
        }
        app.doc_db.init_app(app, config=mongodb_kwargs)

    track_info('(04/08)active more extensions...')
    track_info("       try active CORS rule.")
    if app.config['FANTASY_ACTIVE_CORS'] == 'yes':
        from flask_cors import CORS
        CORS(app, **app.config.get('CORS_KWARGS', {}))
        pass

    track_info("       try active i18n rule.")
    if app.config['FANTASY_ACTIVE_I18N'] == 'yes':
        from flask_babel import Babel
        Babel(app)
        pass

    track_info("       try active celery rule.")
    if app.config['FANTASY_ACTIVE_CELERY'] == 'yes':
        from .celery import Celery
        connect_celery(app, Celery())
        pass

    track_info("       try active oss storage.")
    if app.config['FANTASY_STORAGE_MODULE']:
        st_module_name, st_class_name = app.config[
            'FANTASY_STORAGE_MODULE'].rsplit('.', 1)

        st_module = importlib.import_module(st_module_name)
        st_class = getattr(st_module, st_class_name)

        app.storage = st_class(app)
        pass

    track_info("       try active sentry.")
    if app.config['FANTASY_ACTIVE_SENTRY'] == 'yes':
        try:
            import sentry_sdk
            from sentry_sdk.integrations.flask import FlaskIntegration
            sentry_sdk.init(os.environ['SENTRY_DSN'],
                            integrations=[FlaskIntegration()])
        except Exception:
            from raven.contrib.flask import Sentry
            Sentry(app)
        pass

    track_info("       try active prometheus.")
    if app.config['FANTASY_ACTIVE_EXPORTER'] == 'yes':
        from flask_prometheus_metrics import register_metrics
        register_metrics(app,
                         app_version='v' + version,
                         app_config=app.config['ENV'])

        pass

    track_info("       try active cache.")
    if app.config['FANTASY_ACTIVE_CACHE'] == 'yes':
        redis_kwargs = {
            k.lower().replace('redis_', ''): v
            for (k, v) in app.config.items() if k.upper().startswith('REDIS_')
        }
        import redis
        app.cache = redis.Redis(**redis_kwargs)
        pass

    track_info('(05/08)active something with app context...')
    with app.app_context():

        track_info("       bind sentry trigger handler.")
        if hasattr(mod, 'run_app'):
            run_app = getattr(mod, 'run_app')

            try:
                run_app(app)
            except Exception as e:
                if hasattr(app, 'sentry'):
                    app.sentry.handle_exception(e)
                    pass

                import sys
                import traceback
                traceback.print_exc()
                sys.exit(-1)

            pass

        track_info("       bind auto migrate.")
        if app.db and app.is_root_app:
            track_info(f"              match root-app flag at: {app.name}, "
                       f"will try execute smart migrate.")
            smart_migrate(app)
            pass

        track_info("       try bind account manager.")
        if app.config['FANTASY_ACTIVE_ACCOUNT'] == 'yes' and \
                app.config['FANTASY_ACCOUNT_MANAGER']:
            smart_account(app)
            pass

        track_info('(06/08)bind error handle...')

        @app.errorhandler(400)
        def h_400(error):
            return error_handler.http400(error)

        @app.errorhandler(422)
        def h_422(error):
            return error_handler.http422(error)

        @app.errorhandler(500)
        def h_500(error):
            return error_handler.http500(error)

        if hasattr(mod, 'error_handler'):
            error_handle = getattr(mod, 'error_handle')
            error_handle(app)
            pass

        track_info('(07/08){unstable}bind admin handle...')
        if app.config['FANTASY_ACTIVE_ADMIN'] == 'yes' \
                and hasattr(mod, 'run_admin'):
            import flask_admin

            try:
                admin_name = app.config.get('FANTASY_ADMIN_NAME')
            except KeyError:
                admin_name = 'Admin'

            try:
                admin_tpl_name = app.config.get('FANTASY_ADMIN_TEMPLATE_MODE')
            except KeyError:
                admin_tpl_name = 'bootstrap3'

            admin = flask_admin.Admin(name=admin_name,
                                      template_mode=admin_tpl_name)

            run_admin = getattr(mod, 'run_admin')
            run_admin(admin, app)
            admin.init_app(app)
            pass

        pass

    track_info('(08/08)bind CLI command...')
    track_info("       try bind ff command.")
    if app.config['FANTASY_ACTIVE_CLI'] == 'yes' and app.is_root_app:
        track_info(f"              match root-app flag at: {app.name}, "
                   f"will add ff command.")
        app.cli.add_command(cli.ff)

    track_info("       try bind custom command.")
    if app.config['FANTASY_ACTIVE_CLI'] == 'yes' and hasattr(mod, 'run_cli'):
        track_info(f"              found custom command at: {app.name}, "
                   f"will add custom command.")
        run_cli = getattr(mod, 'run_cli')
        run_cli(app)
        pass

    return app
예제 #11
0
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
from flask_prometheus_metrics import register_metrics

app = Flask(__name__)


@app.route("/index")
def index():
    return "Index Page", 200


@app.route("/health")
def health():
    return "I am healthy", 200


@app.route("/error")
def error():
    return "Internal Server Error!", 500


# provide app"s version and deploy environment/config name to set a gauge
# metric
register_metrics(app, app_version="v0.1", app_config="workshop")

# Plug metrics WSGI app to your main app with dispatcher
dispatcher = DispatcherMiddleware(app.wsgi_app, {"/metrics": make_wsgi_app()})

run_simple(hostname="0.0.0.0", port=5000, application=dispatcher)