0

I have a small flask application which needs some configuration. If something is missing I'd like to "abort" startup so the error will be noticed immediately.

My WSGI script is trivial but maybe it helps to understand my question:

from myapp.startup import init_app
app = init_app()

So say somewhere in ìnit_app() the code finds that something is wrong (e.g. missing configuration values or outdated DB schema version, insecure directory permissions, ...) I'd like to ensure that the application is not run (because it will fail later anyway).

I can throw in a sys.exit(1) somewhere in the code but then flask retries endlessly to start the app (user does not see any page). Of course I could build an alternate WSGI app which shows some text.

But I hoped there would be some kind of "best practice" (and ideally existing Python code so it even looks "nice").

  • Is there a way to tell flask/the WSGI server that the app startup failed and it should not try again?
  • Is there existing code to handle "setup errors"?
Felix Schwarz
  • 2,938
  • 4
  • 28
  • 41

2 Answers2

0

This looks like it might do what you want it to in terms of shutting down the server. http://flask.pocoo.org/snippets/67/

But instead of calling from an endpoint you can call the function when you detect an error in your startup code.

Tim Thompson
  • 301
  • 2
  • 7
  • The link posted in the answer no longer works. Do either of you have the details that were published in that post? I'm running into a similar need. – Phillip Boushy Apr 22 '21 at 22:57
  • Page can be found from an archive @PhillipBoushy http://web.archive.org/web/20190706125149/http://flask.pocoo.org/snippets/67 Taken from the accepted answer from this SO question: https://stackoverflow.com/questions/15562446/how-to-stop-flask-application-without-using-ctrl-c – Zobayer Hasan May 19 '21 at 10:01
0

Stumbled upon a similar problem recently.

Returning a sys.exit(ERRNO) does not help because WSGI servers such as gunicorn will simply keep trying to start another instance.

Raising a RuntimeError will cause the application to abort. I don't think there is a "right way" of doing this, but this way seems pretty pythonic to me.

Something like this:

try:
    SECRET_KEY = os.getenv("FLASK_SECRET").encode("utf-8")
except AttributeError:
    raise RuntimeError("Environment variable $FLASK_SECRET was not set")

Then trying to start the server with gunicorn will fail with errors:

.$ gunicorn -b 0.0.0.0:5000 myapi.wsgi:app
...
...
  File "path/to/myapi/config.py", line 18, in <module>
    raise RuntimeError("Environment variable $FLASK_SECRET was not set")
RuntimeError: Environment variable $FLASK_SECRET was not set
[2021-05-19 16:08:43 +0600] [17567] [INFO] Worker exiting (pid: 17567)
[2021-05-19 16:08:43 +0600] [17565] [INFO] Shutting down: Master
[2021-05-19 16:08:43 +0600] [17565] [INFO] Reason: Worker failed to boot.
.$
Zobayer Hasan
  • 2,187
  • 6
  • 22
  • 38