AJAX on Google App Engine
Continuing my last week’s exploration,
I started to do something a little bit more than things in the Getting Started
tutorial. The tutorial basically shows the way to do traditional server-side web
page processing. In terms of ASP.NET, the way is like coding all logics in a class
implements IHttpHandler in the code-behind. As the reality is that we need dynamic
pages in our web application, I tried to explore the ways to add some AJAX-behaviors
to my web pages.
There isn’t any magic to use AJAX on App Engine (It just serves an incoming request, anyway). The difficult part comes in data serialisation. In an AJAX-enabled environment, you may have to pass a non-trivial amount of data to and from the cloud. With Python and App Engine, how do you parse the data from incoming request as well as prepare data in the response? Should you follow the trend, developers are now using JSON instead of old SOAP-compliant XML (maybe not even plain XML). What I want to do is retrieving some entities from datastore, extracting some of the fields, and encoding the fields into a JSON string.
I’m not giving a tutorial here. Honestly, I’ve never do any Python coding until last week. As a programmer coming from a C# background, the most difficult part is about the language and libraries available. So below is what I’ve done over this weekend.
List and Dictionary
These two are perhaps the most encountered containers. They are mutable. How to declare?
myList = []
myDictionary = {}
Where is my favourite statusMessage = abc == null ? “OK” : “Cancel” syntax?
statusMessage = ‘OK’ if abc == NONE else ‘Cancel’
The get handler
Here, Guest is a model in datastore. Then, I created a query named guests and
a list named json. A for loop is written to iterate through the entities from
datastore and extracted some of the fields to create a dictionary named g. By
the end of iteration, “g” is appended to list json. For client side to retrieve
the data correctly, I’ve to put the whole thing into a dictionary again and that’s
why you see { 'guests': json } in the last line. The work of encoding Python
object to a JSON string is done by a library called simplejson. Thus, you should
have an import statement like this from django.utils import simplejson. Calling
its dumps function is the last thing I have to do.
class GetGuestList(webapp.RequestHandler):
def get(self):
guests = Guest.all().order('lastName')
json = []
for guest in guests:
g = {
'firstName': guest.firstName,
'lastName': guest.lastName,
'isVip': guest.isVip,
}
json.append(g)
self.response.out.write(simplejson.dumps({'guests':json}))
The post handler
I didn’t try using JSON in posting data. But, if you want use it, I guess using
simplejson.loads will be fine. Here, I used the ordinary techniques to post data
back to server side.
class AddGuest(webapp.RequestHandler):
def post(self):
isVip = self.request.get('isVip') == 'true'
guest = Guest(salutation = self.request.get('salutation'),
lastName = self.request.get('lastName'),
firstName = self.request.get('firstName'),
isVip = isVip)
if users.get_current_user():
guest.lastModifiedBy = users.get_current_user()
guest.put()
The dispatcher
application = webapp.WSGIApplication(
[('/', MainPage),
('/addGuest', AddGuest),
('/getGuestList', GetGuestList)],
debug=True)
Here is how I did it.
Happy coding! :)