pythonpython-3.xflaskglobal-variablesflask-appbuilder

How to track a variable whose value keeps changing across the entire lifecycle of flask application?


I have a Flask application which have some endpoints out of which 3 are for managing the Flask app. There is a variable health_status whose value is initially "UP" - string.

/check = checks the status of the flask app. whether it's up or down.

/up = changes the value of a variable to "UP" whose value is used as a check before any request is served

/down = changes the value of a variable to "DOWN"

When the health_status is "UP" the app can serve any endpoints that it is providing. When it is "DOWN", it simply returns 500 error for any API endpoint excep /up endpoint which brings back the server health status (I'm making a check before executing any API call using @app.before_request in Flask).

What I want to know is if this is preferrable. Is there any alternative for doing such task?

health_check.py:

from flask.json import jsonify
from app.common.views.api_view import APIView
from app import global_config

class View(APIView):
    def check(self):
        return jsonify({'status': f"Workload service is {global_config.health_status}"})
    def up(self):
        global_config.health_status = "UP"
        return jsonify({'status': "Workload service is up and running"})
    def down(self):
        global_config.health_status = "DOWN"
        return jsonify({'status': f"Workload service stopped"})

global_config.py:

workload_health_status = "UP"

app/__init__.py:

from flask import Flask, request, jsonify
from app import global_config
excluded_paths = ['/api/health/up/', '/api/health/down/']

def register_blueprints(app):
    from .health import healthcheck_api
    app.register_blueprint(healthcheck_api, url_prefix="/api/health")

def create_app(**kwargs):
    app = Flask(__name__, **kwargs)
    register_blueprints(app)
    @app.before_request
    def health_check_test():
        if request.path not in excluded_paths and global_config.workload_health_status == "DOWN":
            return jsonify({"status": "Workload service is NOT running"}), 500
    return app

Solution

  • You could just use the app's built-in config object and query/update it from anywhere in the application, e.g. app.config['health_status'] = 'UP'. This would obviate the need for your global_config object. Using @app.before_request is probably still the most elegant way to check this value though.