Setting and Getting Cookies in Google’s WebApp

Here’s the disclaimer: I’m currently teaching myself Python for use with Google’s App Engine and (unlike my PHP or Perl) I’m not entirely sure if the below is best practice or even remotely sane, but that said, it does seem to work for me!

Setting a Cookie

Notes: Obviously the code is running in a controller (or rather a Request Handler) that extends webapp.RequestHandler and you’ll notice that I had to use a Regular Expression to remove the header name from Cookie.SimpleCookie’s output so I could tie it in to webapp’s header frame work which should stop any output buffering issues in the future.


import Cookie
import re
import base64

class YourHandler(webapp.RequestHandler):
   cookieName = 'MyCookie'
   domain = ''
   expires = 360
   value = 'Some value or something...'

   def get(self):
         simpleCookieObj = Cookie.SimpleCookie()

         simpleCookieObj[self.cookieName] = str(base64.b64encode(self.value))
         simpleCookieObj[self.cookieName]['expires'] = self.expires
         simpleCookieObj[self.cookieName]['path'] = '/'
         simpleCookieObj[self.cookieName]['domain'] = self.domain
         simpleCookieObj[self.cookieName]['secure'] = ''

         #Cookie.SimpleCookie's output doesn't seem to be compatible with WebApps's http header functions
         #and this is a dirty fix

         headerStr = simpleCookieObj.output()
         regExObj = re.compile('^Set-Cookie: ')
         self.response.headers.add_header('Set-Cookie', str(regExObj.sub('', headerStr, count=1)))

Getting a Cookie

Notes: This is much easier, we just have to make sure that it exists.


import Cookie
import base64

class YourOtherHandler(webapp.RequestHandler):
   cookieName = 'MyCookie'

   def get(self):
      try:
         cookieValue = str(base64.b64decode(self.request.cookies[self.cookieName]))
      except KeyError:
         #There wasn't a Cookie called that
         cookieValue = ''