How to call a function when Apache terminates a Flask process? How to call a function when Apache terminates a Flask process? flask flask

How to call a function when Apache terminates a Flask process?


The best way to add cleanup functionality before graceful termination of a server-controlled Python process (such as a Flask app running in Apache WSGI context, or even better, in Gunicorn behind Apache) is using the atexit exit handler.

Elaborating on your original example, here's the addition of the exit handler doing the cleanup of .pid file:

import atexitimport osfilename = '{}.pid'.format(os.getpid())@app.before_first_requestdef before_first_request():    with open(filename, 'w') as file:        file.write('Hello')def cleanup():    try:        os.remove(filename)    except Exception:        passatexit.register(cleanup)


The simplest way would be to handle this outside of the Apache process. There's no guaranteed way that the process will always remove the files (for example, if you restart the apache server mid-request).

The approach I've taken in the past is to use cron. Write a small script somewhere in your repository and have it executed on a schedule (daily usually works). This script can just clear out all files in the directorty that are older than 24 hours, so you'll always have a rolling window of 1 days worth of files.

This has two benefits:

  1. You're in total control of the script, and can use any language you want.
  2. You can do fancy stuff with these files. You can compress them and store them elsewhere, delete them, or perform analytics on them. Entirely up to you!

Most scripting languages have a small wrapper class that can be used to make cron more friendly. A popular one for Ruby is whenever.