Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching of (fake) static content which is actually dynamic on GAE for Python

In my GAE app I have the following handler in app.yaml:

- url: /lang/strings.js
  script: js_lang.py

So a call to /lang/strings.js will actually map to the js_lang.py request handler which populates the response as application/javascript. I want this response to be cached in the browser so that the request handler only gets called once in a while (for example when I "invalidate" the cache by importing /lang/strings.js?v=xxxx when I deploy a new version of the app.

For normal static content, there is the default_expiration element, which is very handy. And results in http response headers like this:

Expires: Fri, 01 Apr 2011 09:54:56 GMT
Cache-Control: public, max-age=600

Ok, the question: is there an easy way for me to return headers such as this, without having to explicitly set them? Alternatively, is there a code snippet out there that accepts a few basic parameters such as "days" and produces the expected http-headers?

Edit 12 April 2011

I solved this very by simply setting the two headers Expires and Cache-Control like this:

import datetime
thirty_days_in_seconds = 4320000
expires_date = datetime.datetime.now() + datetime.timedelta(days=30)
HTTP_HEADER_FORMAT = "%a, %d %b %Y %H:%M:00 GMT"        

self.response.headers["Expires"] = expires_date.strftime(HTTP_HEADER_FORMAT)
self.response.headers["Cache-Control"] = "public, max-age=%s" % thirty_days_in_seconds
like image 470
Jon Nylander Avatar asked Apr 01 '11 11:04

Jon Nylander


1 Answers

Have a look at Static serving blog post by Nick.

There's everything you need to know about Conditional request and how to properly get and set the correct HTTP headers:

  • Http Request header handling (If-Modified-Since,If-None-Match)
  • Http Response headers handling (Last-Modified, ETag)
like image 82
systempuntoout Avatar answered Sep 30 '22 00:09

systempuntoout