Serving Django media files in OpenShift

As you may already know, setting up a Django instance on the OpenShift platform is a matter of less than 5 minutes.

Through the web management console you can create an  application using the “Python 2.6″ web cartridge thus setting up a gear to host (guess!) a Python enviroment. You clone the gear repository, add the Example App code as a template, push the repo and you’re done.

There’s a folder in gear’s filesystem called data designed to contain files you don’t want to lose among application deployments. This storage is perfect for containing files that users upload through your Django application, and the settings file provided by the Example App is aware of this:

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.environ.get('OPENSHIFT_DATA_DIR', '')

The OPENSHIFT_DATA_DIR environment variable is always available inside your gear and contains the absolute path to the data dir.

File uploads work out of the box but problems arise when you try to access files contained in the MEDIA_ROOT folder -  by default Apache serves the files contained in <app>/wsgi/static but knows nothing about the data dir located at <app>/../, so you will likely get a 404 trying to access files under the MEDIA_URL. To workaround this problem you can redirect requests for MEDIA_URL to STATIC_URL and symlink the data folder from the static folder.

To redirect requests, create a .htaccess file in the <app>/wsgi folder containing exactly these lines:

RewriteEngine On
RewriteRule ^application/media/(.+)$ /static/$1 [L]

If you manually make the symlink in <app>/wsgi/static,  it will be lost on the next deployment (remember? Only data folder won’t change) so you better let OpenShift do it for you during application deployment. Open the file at <app>/.openshift/action_hooks/build and add the following lines:

if [ ! -d $OPENSHIFT_DATA_DIR/media ]; then
mkdir $OPENSHIFT_DATA_DIR/media
fi

ln -sf $OPENSHIFT_DATA_DIR/media $OPENSHIFT_REPO_DIR/wsgi/static/media

That’s it, commit and push the modifications above and grab files from your media folder.

About these ads

3 thoughts on “Serving Django media files in OpenShift

  1. Pingback: SERVING DJANGO MEDIA FILES IN OPENSHIFT « Lushuchao's Blog

Comments are closed.