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 = ''

Changing Default hostname in Google App Engine Launcher

Google App Engine\'s WebApp preferences

These past few weeks I’ve mostly been writing Python for Google’s App Engine and listening to Country Music. They say a change is as good as a holiday, so two changes must be equivalent to a cruise or something.

To cut to the chase, today I was testing some Cookie functionality and needed to run my WebApp on another domain other than localhost and of course, since I was using the App Engine Launcher GUI rather than the command line, I couldn’t find any documentation on how to do it.

To be fair, I didn’t look very hard, I just tried the following:

I added –address= followed by the hostname I wanted to run my WebApp under and low and behold I could access it across my LAN!