Forums

Issue with Shutdown Signal Handling in Flask

Hello everyone,

I am facing an issue with a Flask application that I am running on PythonAnywhere. The code is written to capture shutdown signals (such as SIGTERM and SIGINT) and perform proper resource cleanup, such as closing database connections, when the server is stopped or terminated. However, the shutdown signals are not being captured as expected, and the finalization function is not being called correctly.

Here is a snippet of the code where I try to capture the signals and call the shutdown function:

def shutdown():
    database.close()

def shutdown_handler(signum, frame):
    shutdown()
    sys.exit(0)

signal.signal(signal.SIGTERM, shutdown_handler)
signal.signal(signal.SIGINT, shutdown_handler)
atexit.register(shutdown)

if __name__ == '__main__':
    app.run(debug=True, port=5050)

My question is: is there a reason these signals are not being captured on PythonAnywhere? I have already added logs inside the signal handlers to check if the issue is with signal capturing, but nothing is logged when the server is stopped.

Also, I am running the app with app.run(debug=True, port=5050) during development, but I know this is not recommended for production. I wonder if the behavior is different when the app is running with a WSGI server like gunicorn (which I believe is the default production server on PythonAnywhere).

Has anyone experienced this or have suggestions on what might be preventing the shutdown signals from being captured properly? What would be the best way to ensure a proper shutdown in an environment like PythonAnywhere?

I appreciate any help or suggestions!

PythonAnywhere does not use the Flask development server to run your code, so the process that runs your code is not the process that has the signals sent to it.