Sunday, April 18, 2010

behind the scenes

Some people may wonder how I got my "patterns of doom" app to automatically redirect to the app stats page after a request was executed. The secret is lies in applying a little hack to the app stats framework. On the main documentation site, an appengine_config.py is mentioned that installs the recording mechanism for app stats. I took that script and applied a small modification:

   1: def webapp_add_wsgi_middleware(app):
2: import os
3: from google.appengine.ext.appstats import recording
4: old_init = recording.Recorder.__init__
5: def new_init(self, env):
6: old_init(self, env)
7: link = 'http://%s%s/details?time=%s' % (
8: self.env.get('HTTP_HOST', ''),
9: '/stats',
10: int(self.start_timestamp * 1000))
11: os.environ['STATS_LINK'] = link
12: recording.Recorder.__init__ = new_init
13: app = recording.appstats_wsgi_middleware(app)
14: return app

Basically, I am monkeypatching the constructor of the Recorder class to dump the link it will eventually generate into an environment variable. My request logic can then read that value and use it for redirects. Other applications would also be possible (like creating an asynchronous task that reads the value out and dumps it into another, more persistent state for longer-term analysis), so I thought I'd share the code with anyone interested :-)

0 comments: