Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using additional command line arguments with gunicorn

Assuming I'm starting a Flask app under gunicorn as per http://gunicorn.org/deploy.html#runit, is there a way for me to include/parse/access additional command line arguments?

E.g., can I include and parse the foo option in my Flask application somehow?

gunicorn mypackage:app --foo=bar

Thanks,

like image 835
sholsapp Avatar asked Dec 13 '11 19:12

sholsapp


People also ask

How does Gunicorn handle multiple requests?

If each request takes 10 milliseconds, a single worker dishes out 100 RPS. If some requests take 10 milliseconds, others take, say, up to 5 seconds, then you'll need more than one concurrent worker, so the one request that takes 5 seconds does not "hog" all of your serving capability.

What does Gunicorn command do?

Gunicorn is a pure-Python HTTP server for WSGI applications. It allows you to run any Python application concurrently by running multiple Python processes within a single dyno.

Which is better Gunicorn or uWSGI?

Both can reach very impressive levels of performance, though some have mentioned that Gunicorn works better under high load. Drawbacks to Gunicorn are much the same as uWSGI, though I personally have found Gunicorn to be more easily configurable than uWSGI.

How do I run Gunicorn on another port?

Configure Gunicorn The Gunicorn process will start and bind to all host IP addresses on port 8081. Use control + z to terminate Gunicorn process. Note: The default (host) port can be configured here to use any other open port on which you prefer to expose the Transform. Note: In this case 'python3' must be specified.


2 Answers

You can't pass command line arguments directly but you can choose application configurations easily enough.

$ gunicorn 'mypackage:build_app(foo="bar")'

Will call the function "build_app" passing the foo="bar" kwarg as expected. This function should then return the WSGI callable that'll be used.

like image 65
Paul J. Davis Avatar answered Oct 17 '22 05:10

Paul J. Davis


I usually put it in __init.py__ after main() and then I can run with or without gunicorn (assuming your main() supports other functions too).

# __init__.py

# Normal entry point
def main():
  ...

# Gunicorn entry point generator
def app(*args, **kwargs):
    # Gunicorn CLI args are useless.
    # https://stackoverflow.com/questions/8495367/
    #
    # Start the application in modified environment.
    # https://stackoverflow.com/questions/18668947/
    #
    import sys
    sys.argv = ['--gunicorn']
    for k in kwargs:
        sys.argv.append("--" + k)
        sys.argv.append(kwargs[k])
    return main()

That way you can run simply with e.g.

gunicorn 'app(foo=bar)' ...

and your main() can use standard code that expects the arguments in sys.argv.

like image 26
personal_cloud Avatar answered Oct 17 '22 05:10

personal_cloud