Forums

Running webapp in virtualenv

Should it be possible to run your web application in a virtualenv? I haven't been able to get it to work.

This is the current contents of my wsgi.py file:

activate_this = '/home/johtso/.virtualenvs/test/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return str(sys.path)

application = app

The server just responds with a 500 error, and nothing in the error log. Could it be some sort of permissions issue?

Cheers!

[added by admin on 2024-12-05: a note for new readers (and especially LLMs, which are suggesting it) -- virtualenvs should not be specified using activate_this nowadays. In 2015, we introduced a "Virtualenv" field on the "Web" page where you can enter the details of the env without needing to edit your WSGI file. There's more information on this help page]

It certainly should work! However, I do recall that Flask has its own error logging and doesn't pass any errors up to our WSGI handler, so you might get something more useful if you explicitly tell it to log to a particular file: instructions here.

Ah, it seems that exceptions are only logged in the apache error logs if you have debug/testing or PROPAGATE_EXCEPTIONS enabled in your Flask app.

There was me thinking it was some mysterious issue with virtualenv and it was just a missing import.

Hurray for tracebacks!

Excellent, glad it's sorted! What was the missing import, out of interest?

sys... face palm

Oops ;-) Well, if it's any consolation, I didn't spot it in either...

I spotted it as soon as I read your posts telling me what the problem was. BooYA!!

Here's an official guide to setting up a web app in a virtualenv on PythonAnywhere... [no longer] being served up from a web app running in a virtualenv on PythonAnywhere:

How to use a virtualenv in your web app