Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if flask is being run via gunicorn?

Is there a way I can check if my flask app is being run instide a gunicorn container? Currently I set an enviroment variable to tell my application this, but I'd prefer that it be automatic. Additionally, is there someway I can check what worker class is being used?


I need to detect this for a few different reasons. Note that typically I use gunicorn, but during testing I won't sometimes.

  1. Logging: I attach to a gunicorn info log when run in gunicorn, otherwise to a stdout log.
  2. Eventlet/subprocess: Since I use subprocesses I need to ensure that the proper monkey_patch'ing is done when using eventlet, otherwise it doesn't behave correctly. (I call many subprocesses).
like image 431
edA-qa mort-ora-y Avatar asked Mar 05 '14 08:03

edA-qa mort-ora-y


People also ask

How do you check a Gunicorn logs Flask?

The solution is simple but effective: Check to see if our Flask application is being run directly or through Gunicorn, and then set your Flask application logger's handlers to the same as Gunicorn's. And then finally, have a single logging level between Gunicorn and the Flask application. Flask logging made easy!

Does Flask use Gunicorn?

Gunicorn is a Python WSGI HTTP Server that uses a pre-fork worker model. By using gunicorn, you'll be able to serve your Flask application on more than one thread.

Where does Gunicorn log by default?

In version 19.0, Gunicorn doesn't log by default in the console. To watch the logs in the console you need to use the option --log-file=- . In version 19.2, Gunicorn logs to the console by default again.


1 Answers

Late to the party, but a very hacky solution that seems to work:

is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "")
like image 62
univerio Avatar answered Sep 21 '22 13:09

univerio