David Cramer's Blog

Python, Django, and Scale.

Scaling Your Frontend: Far-Futures Headers and Template Tags

One of the many things we do to help optimize our website load times is optimize the frontend by setting far-futures headers. This simply means that media has an Expires tag of sometime in the distant future (maybe a year), and when we make changes, the filename needs to change. The easiest way to do this, is by adding a simple GET parameter.

To handle this, we had been using a simple revision system, where we just increment a number in a list of files, and it appends that number to the filename. After realizing how lazy we should have been, I quickly rewrote it to grab the file modification time and use that as the revision number.

Anyways, we did this by using a simple template tag (or a global object as it’s known in Jinja), to output the URL to the file, as well as the revision.

1
2
3
4
5
6
7
8
9
10
import os, os.path
from django.conf import settings
from jinja.contrib.djangosupport import register

<p>def mediaurl(value):
fname = os.path.abspath(os.path.join(settings.MEDIA_ROOT, value))
if not fname.startswith(settings.BASE_PATH):
raise ValueError("Media must be located within MEDIA_ROOT.")
return '%s%s?%s' % (settings.MEDIA_URL, value, unicode(int(os.stat(fname).st_mtime)))
register.object(mediaurl)
Now to link our media files it’s quick and painless:
1
2
3
4
5
6
7
8
<!-- iBegin Stylesheets -->
<link rel="stylesheet" type="text/css" media="screen" href="" />
<link rel="stylesheet" type="text/css" media="print" href="" />

<p><!-- JavaScript -->
<script type="text/javascript">BASE_URL = '';</script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>

Comments