Flask health error: {"status": 500, "title": "The live check function could not be imported"}

Viewed 209

I am trying to add health liveness and readiness into Flask API as follows:

from flask import Flask
from flask_healthz import healthz
from flask_healthz import HealthError

app = Flask(__name__)
app.register_blueprint(healthz, url_prefix="/healthz")

def printok():
    print("Everything is fine")

def liveness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

def readiness():
    try:
        printok()
    except Exception:
        raise HealthError("Can't connect to the file")

app.config.update(
    HEALTHZ = {
        "live": "app.liveness",
        "ready": "app.readiness",
    }
)
@app.route("/")
def hello():
    return "Hello World"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

but when I run curl to check it, I get the error "The live function could not be imported":

$ curl localhost:5000/healthz/live
{"status": 500, "title": "The live check function could not be imported"}

or

 $ curl localhost:5000/healthz/ready
{"status": 500, "title": "The ready check function could not be imported"}

it is interesting that this example has already been suggested by this link healthz for flask as working

Any idea why this error occurs? and how can I resolve it?

2 Answers

For me this was due to PYTHONPATH environment variable. The HEALTHZ map values needs to point to the liveliness and readiness methods, for which PYTHONPATH is required.

In my PyCharm's debug, this environment variable was set correctly while in run this was not set. Manual adding this to run fixed this. If you are Dockerizing the application, this will help - https://stackoverflow.com/a/49631407/2112865.

The culprit is this line:

app = Flask(__name__)

It will create an app with the name of the file with your code so if you have named the file for example 'mycheck.py' you will get the same error. I fixed it with this change:

app.config.update(
    HEALTHZ = {
        "live": app.name + ".liveness",
        "ready": app.name + ".readiness",
    }
)

Note that for some reason this won't work either:

app = Flask("app")
Related