Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Flask app running behind Apache HTTPD. Apache is configured to have multiple child processes.

The Flask app creates a file on the server with the file's name equal to its process ID. The code looks something like this:

import os

@app.before_first_request
def before_first_request():
    filename = os.getpid()
    with open(filename, 'w') as file:
        file.write('Hello')

When the child process is killed/ended/terminated I would like the Flask app to remove this file.

It's not terribly important that removal of a file happens, as these files won't take up much space, so if bizarre errors occur I don't need to handle them. But for normal workflow, I would like to have some cleanup when Apache shuts down the Flask process.

Any idea on the best way to do this?

like image 913
steve Avatar asked Apr 20 '15 19:04

steve


People also ask

How do you call a function in a Flask?

A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes.

How do you use async in Flask?

Async functions require an event loop to run. Flask, as a WSGI application, uses one worker to handle one request/response cycle. When a request comes in to an async view, Flask will start an event loop in a thread, run the view function there, then return the result.

Does Flask work with Apache?

A common way of deploying a Flask web application in a production environment is to use an Apache server with the mod_wsgi module, which allows Apache to host any application that supports Python's Web Server Gateway Interface (WSGI), making it quick and easy to get an application up and running.

Is Flask synchronous or asynchronous?

Flask has been claimed as synchronous on many occasions, yet still possible to get async working but takes extra work.


1 Answers

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 atexit
import os

filename = '{}.pid'.format(os.getpid())

@app.before_first_request
def before_first_request():
    with open(filename, 'w') as file:
        file.write('Hello')

def cleanup():
    try:
        os.remove(filename)
    except Exception:
        pass

atexit.register(cleanup)
like image 116
Velimir Mlaker Avatar answered Sep 23 '22 03:09

Velimir Mlaker