Wednesday, June 19, 2013

Setting Up Google App Engine WebApp2 Project in Virtualenv

Python 2.7, virtualenv, Ubuntu 12.04, GAE 1.7.1
This is a short HOW-TO for how I solved my ImportError: no module google.appengine.ext while working in virtualenv.
GAE can be downloaded from here.
To install GAE on Linux, just extract the content to where ever you want. I myself use apps/ directory under my /home/usr directory. Which means, in my case, GAE will be found in /home/usr/apps/google_appengine.
After downloading and extracting GAE to said directory, I create a virtualenv for my project.
Project directory structure:
$ virtualenv ProjectA/ --no-site-packages

I'm running this command from the parent directory of ProjectA. In general you need to specify a full path to the directory that will be the virtual environment.
More info can be found here.
After creating the virtualenv, I create inside ProjectA an src directory structure that will hold all my code. As someone  who comes from Django background, I tend to uphold same architecture in webapp2 (for example, all my models are saved in, as I find it a very good way of coding.
Ok, so far we downloaded our google app engine and created project directory structure.
Lets activate our virtualenv:
$ cd ProjectA/
$ source bin/activate

So now we have a clean development environment with latest python and pip ready and working.
As someone who practice TDD way of coding, my first pip command is:
(ProjectA)$ pip install nose
This will install latest nose framework for testing in python. And here is a catch, nose will search your whole project directory to find tests, but only in package directories or test directory (more info here), so either create a directory that will match testMatch of nose or make your app a package. When you use Django, it is done automatically for you, but in GAE it's not a must for your app to run. Adding to your app directory will solve it.
To link the GAE we downloaded before to this virtualenv, add gae.pth to /lib/python2.7/site-packages with following content:
<full path to GAE directory>
<full path to GAE directory>/google
<full path to GAE directory>/lib/antlr3
<full path to GAE directory>/webapp2
<full path to GAE directory>/lib/yaml/lib

That's it. Now you can use commands like 'from goole.appengine.ext import ndb'.
Run a few tests on your code, if you see any more GAE connected ImportError, just add the path to needed module to gae.pth.

No comments:

Post a Comment