jfoliveira
jfoliveira

Reputation: 2168

Global gunicorn and pipenv virtual env: ModuleNotFoundError: No module named 'django'

I'd like to have gunicorn only installed globally (apt-get gunicorn3, Ubuntu 18.04) but recognizing my virtual environments managed by pipenv.

This works - local gunicorn:

# install dependencies from requirements.txt
$ pipenv install

# add local gunicorn
$ pipenv install gunicorn

# run the app, using local gunicorn
$ gunicorn my-site.wsgi:application

This doesn't work, and that's what I really need:

# install dependencies from requirements.txt
$ pipenv install

# activate the virtual environment
$ pipenv shell

# run the app, using global gunicorn
$ gunicorn3 my-site.wsgi:application

Error:

[2020-03-18 17:04:31 +0000] [33871] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker
    worker.init_process()
  File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 126, in init_process
    self.load_wsgi()
  File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load
    return self.load_wsgiapp()
  File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 377, in import_app
    __import__(module)
  File "/home/user/my-app/my-site/wsgi.py", line 10, in <module>
    from django.core.wsgi import get_wsgi_application
ModuleNotFoundError: No module named 'django'
[2020-03-18 17:04:31 +0000] [33871] [INFO] Worker exiting (pid: 33871)

As I have multiple python apps in the same server, and some of them cannot be modified to have gunicorn as a requirement, being able to run gunicorn3 globally and start more than one application with pipenv would be very convenient.

What am I missing to be able to run gunicorn globally but still load packages installed in a virtual environment?

Upvotes: 0

Views: 2237

Answers (2)

Christian Melius
Christian Melius

Reputation: 1

I had the same problem and found it was caused by a -s in the shebang of /usr/bin/gunicorn:

#! /usr/bin/python3 -s

The -s causes the apt-get-installed gunicorn not to use the venv. man python3 says:

-s Don't add user site directory to sys.path.

So just override the shebang by running:

/usr/bin/python3 gunicorn my-site.wsgi:application

Upvotes: 0

David Shusterman
David Shusterman

Reputation: 56

run

pipenv run gunicorn my-site.wsgi:application

instead of

gunicorn my-site.wsgi:application

Upvotes: 2

Related Questions