Wednesday, December 17, 2008

Templates in google appengine

Externalizing html from core business logic is very good technique to create code simple and understandable. Embedded HTML in code is difficult to maintain. To Avoid embedded HTML in code python provides us different templating systems which are EZT, Cheetah, ClearSilver, Quixote, and Django , which are supported by google appengine. We use Django template engine in our example.
Create Model class with name

from google.appengine.ext import db

class Message(db.Model):

content = db.TextProperty(required=True)

who = db.StringProperty()

when = db.DateTimeProperty(auto_now_add=True)


class MainHandler(webapp.RequestHandler):

def get(self):

messages = db.GqlQuery('SELECT * FROM Message '

'ORDER BY when DESC').fetch(100)

values = {'messages': messages}

self.response.out.write( template.render('list.html', values))

def main():

application = webapp.WSGIApplication([('/', MainHandler)], debug=True)


if __name__ == '__main__':





.even {



.odd {






<table width="100%" cellspacing="0" cellpadding="0" >

{% for message in messages %}

<tr class="{% cycle even,odd %}" >

<td colspan="3">

<table width='100%' border=1>


<tr class="{% cycle even,odd %}">

<td width="20%" valign="top">Nick</td>

<td align="right" width="20%" valign="top">{{message.when}}</td>


<tr height="40">

<td width="20%" valign="top">{{message.who}} </td>

<td width="80%" valign="top">{{message.content}}</td>






<tr height="5px"><td colspan='3' align='center'> </td></tr>

{% endfor %}




create app.yaml
application: template

version: 1

runtime: python

api_version: 1

- url: /.*


What the above code does

  1. In file we define a model Message with three properties: content,who and when which plays a role of domain object and a db.This is part of App Engine not a python and It uses App Engine big table infrastructure which takes care of all of the distribution, replication and load balancing.

    for detail refrence of entities and model visit
  2. In we define MainHandler class which serve as request handler of all get requests.We use GQL in our code for getting all message model objects. After fetching all results we assign these meesage to values and reponse back to list.html page. self.response.out.write use for writing reponse and template.render method use for rendring list template.
  3. After that we create html file with the name of list.html .In this html file we use Django script for manupolation Message objects. {% for message in messages %} is just foreach like code structure and "{% cycle even,odd %}" uses for applying style class alternatively each time. you can use any number of values, separated by commas for alternatively.

No comments: