1078030: tornado_static

Added 6 years ago by Peter Bengtsson


4 Add your love!



This is the utility script I use on Kwissle to make static files served in an ideal way. It's very much "my way" of doing things and doesn't have any unit tests of its own so I've never bothered to release it as an open source package. If people like I might wrap this up properly.

How to use it:

First this is what it looks like in your template:

<link rel="stylesheet" media="print" href="{% module StaticURL("css/print.css") %}">
{% module StaticURL("css/style.css") %}
.lock { background-image:url('{{ modules.Static64("images/locked.gif") }}') }   
{% module Static("js/ext/jquery.js", "js/foo.js") %}

What you get is something like this:

<link rel="stylesheet" media="print" href="/static/css/print.1235678.css">
<link rel="stylesheet" href="/static/css/style.1235678.css">
.lock { background-image:url('data:image-png;base64,iVBORw0KGgoAA...') }
<script src="/static/js/jquery.foo.123456789.js"></script>

Those numbers you see in there are timestamps which means that you never ever have to worry about serving aggressive cache headers on stale resource.

How to configure it

As you might see if you read the code or try to use it, it depends on a bunch of things. Most of it is pretty obvious. Here's a quick copy-n-paste from my app.py file where the application is set up

class Application(tornado.web.Application):
    def __init__(self,...
        if options.dont_combine:
            ui_modules_map['Static'] = ui_modules_map['PlainStatic']
            ui_modules_map['StaticURL'] = ui_modules_map['PlainStaticURL']

            cdn_prefix = [x.strip() for x in file('cdn_prefix.conf')
                             if x.strip() and not x.strip().startswith('#')][0]
            #logging.info("Using %r as static URL prefix" % cdn_prefix)
        except (IOError, IndexError):
            cdn_prefix = None

        # unless explicitly set, then if in debug mode, disable optimization
        # of static content
        if optimize_static_content is None:
            optimize_static_content = not options.debug

        handlers = route.get_routes()
        app_settings = dict(
            static_path=os.path.join(os.path.dirname(__file__), "static"),
                                  "static", "compiler.jar"),
                                  "static", "yuicompressor-2.4.2.jar"),
        tornado.web.Application.__init__(self, handlers, **app_settings)

Something like that.

File: tornado_static.py