Using the Django framework for Python

This page is showing a generic answer.
To see a more detailed answer customized for you, type your domain name here:

You can use the Django framework for Python on our servers.

This page shows how to get Django scripts to respond to requests (it’s not a complete tutorial). It assumes you’re comfortable using the command-line shell.

The information below is a generic example. Please enter your domain name in the box at the top of this page to see the correct code for your account.

The first thing to do is install the “flup” module that Django needs to handle WSGI requests. Run this from the command-line shell:

pip3 install flup

Now install Django:

pip3 install Django

After that, create a new Django project by running:

cd ~/html/
~/.local/bin/django-admin startproject mysite

Then create this file named yourapplication.fcgi at “my-site/yourapplication.fcgi” (you can use an editor like vi, with vi mysite/yourapplication.fcgi):

#!/usr/bin/python3
import os
import sys
from flup.server.fcgi import WSGIServer
from django.core.wsgi import get_wsgi_application

sys.path.insert(0, '/var/www/html/ex/example.com/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
application = get_wsgi_application()
WSGIServer(application).run()

Now make the “yourapplication.fcgi” file executable, which you can do from the command-line shell with this command:

chmod 0755 mysite/yourapplication.fcgi

Finally, add .example.com to the ALLOWED_HOSTS line of mysite/mysite/settings.py, so that it looks like:

ALLOWED_HOSTS = [ '.example.com' ]

After doing this, the script should work if you load it as https://example.com/mysite/yourapplication.fcgi/. (You’ll probably see a “DisallowedHost” error, but that’s an error from Django that shows that it’s working. The normal Django instructions will help you solve that.)

Can I hide “/yourapplication.fcgi/” at the end of the URL?

You can make the script work when loaded as just https://example.com/mysite/ if you add this .htaccess file to the upper “mysite” directory:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /mysite/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]
</IfModule>

Then restart Django as described below.

How can I force Django to quickly reload when I make a change to a script?

One of the reasons Django is so efficient is that it reads the application’s Python files once when it starts, but doesn’t read them again for each web request it handles.

This can be frustrating if you’re trying to make small live changes when you’re developing a script from the command-line shell — you want to see the changes instantly, without waiting until it decides to read your files again.

The simplest way to solve this is to terminate the running copy of Python after you make any change. Run this:

pkill -f python

After you do that, the next web request will read the changed copy of the files.