Gunicorn--how to kill a worker if the client closes their connection? Gunicorn--how to kill a worker if the client closes their connection? flask flask

Gunicorn--how to kill a worker if the client closes their connection?


Killing a flask worker can be done with this code:

from flask import requestdef shutdown_server():    func = request.environ.get('werkzeug.server.shutdown')    if func is None:        raise RuntimeError('Werkzeug server doesn't run flask')    func()    @app.route('/shutdown', methods=['GET'])def shutdown():    shutdown_server()    return 'Shutting down...'

For killing a Gunicorn server on Linux, you can use this command, which I tested:

pkill gunicorn

This command works flawlessly on all kinds of Linuxes, which I assume you have installed for server

Or if I give you a Python implementation:

import osdef shutdownGunicorn():    os.system("pkill gunicorn")

I don't think killing after request is done would be smart, because then you couldn't know when you will get next request.

Flask doesn't take much CPU and RAM usage while it's not working!

Hope that gives you an answer!