Linux – Deploying Flask application with nginx, uWSGI and virtualenv

linuxnginxuwsgivirtualenv

I'm having a lot of trouble to deploy a Flask application on a CentOS 6 server. I know a few other questions have been asked concerning this problem, but I haven't succeeded yet.

Description

Default Python is Python 2.6.6
nginx version is 1.0.15
uWSGI version is 1.2.5
My virtualenv folder is /home/me/dev/.venv
My virtualenv Python version is 2.7.3 (I want to run Python 2.7.3 with uWSGI)
My app.run() Python file is /home/me/dev/runserver.py
My files, modules, classes, etc. are under /home/me/dev/contacts

What I tried

Here is the relevant part of the nginx.conf :

server {
listen 80;
    access_log off;
    # ...

    location / {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3031;
    }
}

Here is the full runserver.py :

from contacts import app

if __name__ == "__main__":
    app.run()

As per the documentation, I tried to run the following command :

uwsgi -H .venv/ -s 127.0.0.1:3031 -w runserver:app

I have however two problems :
– uWSGI still runs on the Python 2.6.6 version
– I have a 'import site' failed error
– I have a ImportError: No module named flask error, which is most likely linked to the precedent error

I also tried the following command, from the Quickstart tutorial on uWSGI official website :

uwsgi --socket 127.0.0.1:3031 --file runserver.py --callable app --processes 2 -H .venv/

But I have the same exact problems as before.

I am completely lost at the moment, I have tried other commands, but I can't figure out what else I should do.

What could I do to run uWSGI from my virtual environment?

Edit : Ok, so after a few other tries, I've managed to run my application by installing uWSGI in my virtualenv and running it from the activated environment (commands for those who may stumble on my posts and find it an acceptable solution) :

$ . .venv/bin/activate
$ which uwsgi
/home/me/dev/.venv/bin/uwsgi
$ uwsgi -s :3031 -w runserver:app -H .venv/

Should I always run uwsgi from the virtual environment? Isn't there any cleaner way to do it?

Best Answer

I have always install uwsgi in my virtualenv. It is much cleaner that way and if you run multiple apps you can install uwsgi in multiple ways.

I think you are stumbling above by not setting your python path correctly so it has no idea where flask is installed since it isn't searching for it in your virtualenv. Same with your site file.