Django system-wide install to virtualenv

时间:2016-11-26 18:34:38

标签: python django virtualenv gunicorn pythonpath

I've recently deployed an application online using DigitalOcean single-click droplet setup which setup Django on Ubuntu with nginx and gunicorn. It came with a default django project which I've managed to change to my own. However, the default project doesn't use a virtualenv, it uses a system-wide install. So, the app only works if all the dependencies are installed on the system. I know this because if I uninstall django, it gives me an internal server error.

I would like to use the python in my virtualenv as the interpreter. And refer to the site-packages in that environment. I've tried fiddling with the PYTHONPATH and adding sys.path.append('/home/env/projectname') to the wsgi file but this doesn't work.

How can I achieve this?

/etc/init/gunicorn.conf:

setuid django
setgid django
chdir /home/env/projectname

exec gunicorn \
    --name=prj \
    --pythonpath=prj \
    --bind=127.0.0.1:9000 \
    --config /etc/gunicorn.d/gunicorn.py \
    prj.wsgi:application

2 个答案:

答案 0 :(得分:0)

  1. 不要使用名称" venv"对于virtualenvs,因为venv是一个相似但不同的东西。 " VENV"和" virtualenv"是创造孤立环境的不同方式; venv是一种新的方式,但它仅适用于Python 3.3及更高版本,因此virtualenv仍然被更广泛地使用。
  2. 为了避免混淆,请记住virtualenv(和venv,就此而言)的名字很糟糕。没有什么虚拟的。最好将其称为孤立环境。
  3. 现在,gunicorn是一个Python程序。 没有运行你的Django项目;它导入你的Django项目。所以你不可能在不同的环境中运行gunicorn和你的Django项目,因为它们实际上是一个程序。在特定的隔离环境中运行Django项目的方法是在孤立的环境中启动gunicorn:

    source your_virtualenv_dir/bin/activate    
    exec gunicorn ...
    

    要使其工作,您必须在virtualenv中安装gunicorn,或者您必须在系统范围内安装gunicorn并使用--system-site-packages创建virtualenv。

    另见this article of mine

答案 1 :(得分:0)

尝试将gunicorn安装到virtualenv并从那里运行它来设置工作目录并传递wsgi:application。 This tutorial可能会对您有所帮助。 This tutorial也可能有用。