Setting Up virtualenv

Basically a virtualenv is a “virtual environment” for python that contains its own python installation with separate libraries from the global python installation.

  • Set up a virtualenv in your public_html folder by running virtualenv <~yourUsername>/public_html/yourDir>. This will create a folder with virtual python environment.
  • Before installing any other Python packages, go to the directory you created and run source bin/activate. This changes all the python commands to use the virtualenv.
  • Next you need to install both Flask and Web Server Gateway Interface(wsgiref) in your new virtual environment.  
    • cd into the directory and run
      • pip install flask
      • pip install wsgiref

Creating a Flask Application

In a new python file index.py:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
   return 'testing'
if __name__ == '__main__':
   app.run(debug = True)

You can run the app on localhost running python index.py. You will be given an address that you can plug into your web browser and go visit as long as you are on a machine directly wired into our network. Running python index.py will also let you do a quick debug to check for typos, etc.

CGI

To actually host your flask site on web.cecs.pdx.edu, you will need to set up a Common Gateway Interface (CGI).

NOTE:

  • Make sure in advance that any app.run() calls you might have are inside an if __name__ == ‘__main__’ block.
  • Do not use print , it will break the CGI by writing into the http response
  • Do not use sys.stdout, it will also break CGI by writing into the http response.

Creating a .cgi file

In a file named  index.cgi within the same directory as your index.py:

#!/usr/bin/python3

from wsgiref.handlers import CGIHandler
from index import app
CGIHandler().run(app)

Create a .htaccess file

A .htaccess file will serve your page from whatever directory you have stored it in. If you wish to have your homepage redirect to your flask site, put your .htaccess in your public_html folder.

In a file named  .htaccess put:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /~yourUsername/yourDir/index.cgi/$1 [L]

NOTE:

Make sure permissions are set correctly. All files you wish to make available via the www must be world readable, and all directories those files reside in must be world executable:

chmod 644 ~/public_html/index.html
chmod 644 ~/public_html/.htaccess

You should now be able to access your site at web.cecs.pdx.edu/~yourUsername