Wednesday, January 25, 2012

Setting Cookie Expiration in WebApp2

In my previous post, I mentioned briefly that in IE browsers, cookie expiration need to be set by using 'expires' value, instead of 'max_age' value.

Currently, if you are using webapp2 with Google App Engine 1.6.1, you can only specify 'max_age' in the cookie, but not the 'expires' value. Because of  this, your cookies will always become session cookies in IE (expires when the browser is closed), but will have correct expiration in other browsers, eg. Firefox, Chrome, and Safari.

I posted a question in webapp2 forum about this issue, and after some back and forth conversations with Rodrigo Moraes, I got the solution for this. Here's the rundown:

set_cookie is a method defined in webob library, that is shipped with Google App Engine 1.6.1. The version that is included in GAE 1..6.1 is webob 0.9 that does not support setting 'expires' parameter in cookies. However, the later version of webob (v1.1) does support this. And what's great is that when specifying cookie with 'max_age', webob(v1.1) will set the 'expires' value too. So now your cookie will expire correctly in IE as well as in other browsers. Awesome!

The next question then, how do you configure your existing application to use the latest version of webob instead of the one that is shipped with GAE 1.6.1?

There are a couple options. If you are using Python 2.7 runtime with appengine, you can configure your app to use the latest version of webob by adding the following simple lines to your app.yaml file.

- name: webob
  version: latest

If you are using Python 2.5 runtime instead, you will have to download webob from github, and just add it within your application directory.

Note that webob 1.1 is not backward compatible with webob 0.9, so I recommend doing a lot of testing after you updated the library.

1 comment:

  1. I think you already know this, but be very careful using 'latest' in your YAML. It shouldn't be used for production code.

    If they release a version 1.2, for example, your app will be using that version as soon as this becomes available on GAE, whether you ask for it or not.

    As the documentation recommends, it's best to use a specific version number.