'How can I run/test Gunicorn with a Python app locally?
I have a Python project that I inherited that is failing in our pipeline because of Worker terminated due to signal 9.
I assume it has something to do with Gunicorn but I'm not sure how to replicate it locally. I've tried reading the Gunicorn documentation and it doesn't make sense.
Gunicorn is in the requirements.txt file. I don't see anywhere in the project where Gunicorn is referenced/imported. The closest file is config.py.
It says with Gunicorn installed, I should be able to use the gunicorn command, yet that doesn't work for me. It says that command doesn't exist or something along those lines.
Solution 1:[1]
This works, but I still need to figure out how to shut it down... you can send a signal but I'd prefer something nicer.
pip install gunicorn
Then in a py file:
from _pytest.monkeypatch import MonkeyPatch
from unittest import mock
import threading
import gunicorn.app.wsgiapp
def gunicornapp():
args = ['gunicorn', 'main:app']
MonkeyPatch().setenv('FLASK_SECRET_KEY', 'hello')
MonkeyPatch().setenv('FLASK_ENV', 'development')
with mock.patch.object(sys, 'argv', args):
return gunicorn.app.wsgiapp.WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]")
app = gunicornapp()
thread = threading.Thread(target=app.run())
thread.start()
Solution 2:[2]
gunicorn is not part of the application in the same way as other dependencies, it is more like pip or pylint in that it is a command line tool.
If you are running on a UNIX based operating system and have installed it as a requirement you can run it as Mark mentions with the command below in your terminal (e.g. Bash, not an interactive python session).
gunicorn myapp:app
myapp would be the name of the file which contains the entry point for the program. app is the name of the function or variable that contains the response. If you are using falcon in the project it may be a file containing something like
app = falcon.App()
Or from gunicorn's documentation with some annotation:
# Install the dependency
$ pip install gunicorn
# create a file myapp.py with a definition for an app function
$ cat myapp.py
def app(environ, start_response):
data = b"Hello, World!\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(data)))
])
return iter([data])
# run gunicorn with the file myapp and the function app
$ gunicorn -w 4 myapp:app
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NotoriousPyro |
| Solution 2 | James Dewes |
