Beispiel #1
0
def create_app() -> Flask:
    app = Flask(__name__)

    # Always use dev config
    app.config.from_object('config_dev')

    # *Should* load prod config when deployed into Docker container
    if os.getenv('LEARN_FLASK_CONFIG') is not None:
        app.config.from_envvar('LEARN_FLASK_CONFIG')

    # Set logging
    log_file = app.config['LOG_LOC'] + app.config['LOG_FILE']
    logging.basicConfig(level=app.config['LOG_LEVEL'],
                        format=('%(levelname)s %(asctime)s %(name)s '
                                'LrnFlsk %(threadName)s: %(message)s'),
                        datefmt='%Y-%m-%d %H:%M:%S',
                        filename=log_file)

    # Register blueprints
    app.register_blueprint(bye, url_prefix='/bye')
    app.register_blueprint(hello, url_prefix='/hello')
    app.register_blueprint(sqs, url_prefix='/sqs')

    # Setup system check endpoints
    health = HealthCheck()
    envdump = EnvironmentDump()

    app.add_url_rule('/healthcheck',
                     'healthcheck',
                     view_func=lambda: health.run())
    app.add_url_rule('/environment',
                     'environment',
                     view_func=lambda: envdump.run())

    return app
Beispiel #2
0
def add_health_check(app):
    health = HealthCheck()
    envdump = EnvironmentDump()

    health.add_section("application", application_data)
    envdump.add_section("application", application_data)

    app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run())
    app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())
Beispiel #3
0
    def test_should_return_safe_environment_vars(self):
        os.environ['SOME_KEY'] = 'fake-key'

        ed = EnvironmentDump()
        message, status, headers = ed.run()

        jr = json.loads(message)
        self.assertIsInstance(jr["process"]["environ"], Mapping)
        self.assertEqual("********", jr["process"]["environ"]["SOME_KEY"])
Beispiel #4
0
    def test_custom_section_signature(self):
        def custom_section():
            return "My custom section"

        ed = EnvironmentDump(custom_section=custom_section)

        message, status, headers = ed.run()

        jr = json.loads(message)
        self.assertEqual("My custom section", jr["custom_section"])
Beispiel #5
0
    def test_basic_check(self):
        def custom_section():
            return "My custom section"

        ed = EnvironmentDump()

        ed.add_section("custom_section", custom_section)

        message, status, headers = ed.run()

        jr = json.loads(message)
        self.assertEqual("My custom section", jr["custom_section"])
 def execute(self, petisco: Petisco) -> Result[Dict, Error]:
     try:
         application_info = {"config": petisco.info}
         envdump = EnvironmentDump(
             include_python=self.include_python,
             include_os=self.include_os,
             include_process=self.include_process,
         )
         envdump.add_section("Environment", application_info)
         envdump_result = envdump.run()
     except Exception as e:
         return Failure(EnvironmentProviderError(str(e)))
     return Success(json.loads(envdump_result[0]))
Beispiel #7
0
def create_app():
    app = Flask(__name__)

    health = HealthCheck()
    envdump = EnvironmentDump()

    CORS(app)

    blueprint = Blueprint('api', __name__)
    api.init_app(blueprint)
    api.add_namespace(hello_world_ns, '/hello-world')
    app.register_blueprint(blueprint)
    app.add_url_rule("/health-check", "healthcheck", view_func=lambda: health.run())
    app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())

    return app
Beispiel #8
0
def create_app(test_config=None):
    log.info("Creating python app "+__name__)
    flask_app = Flask(__name__)
    flask_app.config.update(settings.PROPS)

    if test_config is not None:
        flask_app.config.update(test_config)
    flask_app.register_blueprint(api_blueprint, url_prefix='/api')

    if test_config is None:
        if flask_app.config.get("COGNITO_CHECK_TOKEN_EXPIRATION") is False:
            log.warning("COGNITO_CHECK_TOKEN_EXPIRATION is disabled, ensure it is enabled in production environments.")
        if flask_app.config.get("FLASK_DEBUG") is True:
            log.warning("FLASK_DEBUG is enabled, ensure it is disabled in production environments.")

    # db initialization
    try:
        db.init_app(flask_app)
    except Exception as e:
        log.exception("Failed to initialize APP: {}".format(repr(e)), exc_info=True)

    # Migrations (upgrade to the latest version)
    with flask_app.app_context():
        try:
            from flask_migrate import upgrade as _upgrade
            migrate = Migrate(flask_app, db)
            _upgrade()
        except Exception as e:
            log.exception("Failed to upgrade DB: {}".format(repr(e)), exc_info=True)

    health = HealthCheck()
    env_dump = EnvironmentDump(include_python=True,
                               include_os=True,
                               include_process=True)
    health.add_check(db_health)
    application_data = settings.application_data()
    # application_data['verified_aws_credentials'] = verify_aws_credentials()
    log.info(application_data)
    env_dump.add_section("application", application_data)
    env_dump.add_section("features", settings.features())

    # Add a flask route to expose information
    flask_app.add_url_rule("/health", "healthcheck", view_func=lambda: health.run())
    flask_app.add_url_rule("/info", "environment", view_func=lambda: env_dump.run())

    return flask_app
Beispiel #9
0
def create_app():
    app = Flask(__name__)

    health = HealthCheck()
    envdump = EnvironmentDump()

    CORS(app)

    blueprint = Blueprint('api', __name__)
    api.init_app(blueprint)
    api.add_namespace(drawee_event_ns, '/draweeEvent')
    app.register_blueprint(blueprint)
    app.add_url_rule("/health-check",
                     "healthcheck",
                     view_func=lambda: health.run())
    app.add_url_rule("/environment",
                     "environment",
                     view_func=lambda: envdump.run())

    db = DBContext(engine).__enter__()
    Migrate(app, db)

    return app
Beispiel #10
0
health = HealthCheck()

envdump = EnvironmentDump()


def database_available():
    return True, "database ok"


health.add_check(database_available)

# Add a flask route to expose information
app.add_url_rule("/arbolbinario/healthcheck",
                 "healthcheck",
                 view_func=lambda: health.run())
app.add_url_rule("/arbolbinario/environment",
                 "environment",
                 view_func=lambda: envdump.run())


def run_rest_server():
    app.run(host=vhost,
            port=vport,
            debug=vdebug,
            threaded=True,
            use_reloader=False)


if __name__ == '__main__':
    run_rest_server()
Beispiel #11
0
#
# client = glog.Client()
# client.setup_logging()


import logging

model = tf.keras.models.load_model('sentiment_analysis.hdf5')
logging.info("model loaded")
text_encoder = tfds.features.text.TokenTextEncoder.load_from_file('sa_encoder.vocab')

app = Flask(__name__)
health = HealthCheck()
envdump = EnvironmentDump()
app.add_url_rule("/health", "healthcheck", view_func=lambda: health.run())
app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())

def application_data():
    return {"maintainer": "Varsha Chawan",
            "git_repo": "https://github.com/varsharanichawan"}

envdump.add_section("application", application_data)

# add your own check function to the healthcheck
def model_available():
    if model and text_encoder:
        return True, "Model and Vocab ok"


health.add_check(model_available)