AppEngine Environment in IPython 1

Posted by dacc on October 05, 2009

While developing BikeJibe, I wanted to do exploratory programming from IPython. Googling “appengine ipython” turns up a cool post on a modified version of the Django “manage.py shell” for the AppEngine environment, but nothing for those using other frameworks.

Here is a script I wrote called “gae-env-setup.py” Basically I culled code from the nosetest project and stuck it in a script you can pass to IPython to setup your app for exploration from the shell.

import sys
 
sys.path.extend([
  '/usr/local/google_appengine/lib/webob',
  '/usr/local/google_appengine/lib/django',
  '/usr/local/google_appengine/lib/antlr3',
  '/usr/local/google_appengine/lib/yaml/lib',
  '/usr/local/google_appengine/',
])
 
from google.appengine.tools import dev_appserver
from google.appengine.tools.dev_appserver_main import *
 
option_dict = DEFAULT_ARGS.copy()
option_dict[ARG_CLEAR_DATASTORE] = True
 
config, matcher = dev_appserver.LoadAppConfig(".", {})
dev_appserver.SetupStubs(config.application, **option_dict)
 
import bikejibe.main
reload(bikejibe.main)
 
from webtest import TestApp
SAFARI4_UA = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9"
app = TestApp(bikejibe.main.application(), extra_environ={"HTTP_USER_AGENT": SAFARI4_UA})
 
from lxml import etree
from StringIO import StringIO
 
def parseResponse(response):
  parser = etree.HTMLParser()
  return etree.parse(StringIO(response.body), parser)
 
import bikejibe.model
reload(bikejibe.model)
 
from bikejibe.model import *

Now you can interact with the datastore, make requests to your app, etc. Also, etree allows you to inspect your pages using xpath, etc. Note that all of this is without running dev_appserver independently! I just pass in the WSGI app and away we go.

In [38]: %run gae-env-setup.py
WARNING:root:Could not read datastore data from /tmp/dev_appserver.datastore
WARNING:root:Could not read datastore data from /tmp/dev_appserver.datastore.history
WARNING:root:Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: No module named _imaging
 
In [39]: index = app.get("/")
 
In [40]: doc = parseResponse(index)
 
In [41]: doc.xpath("//option")[0].text
Out[41]: "Where's my region?"
 
In [42]: r = Region(name="Portland")
 
In [43]: r.put()
Out[43]: datastore_types.Key.from_path(u'Region', 1, _app_id_namespace=u'bikejibe-local')
 
In [44]: index = app.get("/")
 
In [47]: doc = parseResponse(index)
 
In [48]: doc.xpath("//option")[0].text
Out[48]: 'Portland'

Enjoy!

Trackbacks

Use this link to trackback from your own site.

  • Yaocl
    Cool.
    It is very useful for appengine development.
blog comments powered by Disqus