Search code examples
pythontornadohttp-caching

Tornado does not check if Javascript files are updated without updating index


I'm using Tornado to serve and HTTP file that uses multiple JavaScript files like this:

<script src="static/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="static/js/stream.js" type="text/javascript"></script>
<script src="static/js/d3.min.js"></script>
<script src="static/js/d3.slider.js"></script>

Unfortunately, when I change these files, it doesn't realize that they've changed and continues to respond with 304 responses. I tried stopping these responses by disabling caching, but that didn't work.

Is there some other setting I'm supposed to be setting in Tornado? Is this a bug I should report?


Solution

  • Use RequestHandler.static_url. It will return a versioned url (by default appending ?v=), which allows the static files to be cached indefinitely.

    Steps to enable it:

    1. Define static_path in your settings, it is directory from which static files will be served:

      settings = {
          'static_path': '/var/www/static/',
          # other settings
      }   
      
    2. Provide this settings to your application:

      app = tornado.web.Application(settings=settings, **kwargs)
      
    3. Use static_url in templates:

      <script src="{{ static_url('js/jquery-1.11.0.min.js') }}" type="text/javascript"></script>
      <script src="{{ static_url('js/stream.js') }}" type="text/javascript"></script>
      <script src="{{ static_url('js/d3.min.js') }}"></script>
      <script src="{{ static_url('js/d3.slider.js') }}"></script
      

    The output will be something like (check those ?v=hash)

        <script src="/static/js/jquery-1.11.0.min.js?v=12d" type="text/javascript"></script>
        <script src="/static/js/stream.js?v=34a" type="text/javascript"></script>
        <script src="/static/js/d3.min.js?v=df3"></script>
        <script src="/static/js/d3.slider.js?v=ad1"></script