Skip to content
Cristian Carpenter edited this page Nov 17, 2017 · 40 revisions

Backbone.js Google App Engine

Backbone.js + Google App Engine

Working demo here: http://todolist-app.appspot.com/

Code here: https://github.com/ccarpenterg/todolist

I'm just learning to use the Backbone.js JavaScript framework and I was curious about making it work with Google App Engine. So I took the Todos example application and started to play.

Backbone.js connects to your application over a RESTful JSON interface. And everything you have to know about how to construct the RESTful Handler is in the Backbone.sync documentation.

From the Backbone.js documentation:

  • read -> GET /collection[/id]
  • create -> POST /collection
  • update -> PUT /collection/id
  • delete -> DELETE /collection/id

So I've created a RESTful handler with one function for each HTTP method (main.py):

class RESTfulHandler(webapp.RequestHandler):
    def get(self, id):
        ...
    def post(self, id):
        ...
    def put(self, id):
        ...
    def delete(self, id):
        ...

In order to point the collection to the GAE Datastore I've removed the backbone-localstorage.js file dependency and mapped the collection to the url /todos (todos.js).

window.TodoList = Backbone.Collection.extend({

    // Reference to this collection's model.
    model: Todo,

    // Save all of the todo items under the `"todos"` namespace.
    //localStorage: new Store("todos"),

    url: '/todos',

Then I mapped the URL path to the RESTfulHandler (main.py):

application = webapp.WSGIApplication(
				     [('/', MainHandler),
				      ('/todos\/?([0-9]*)', RESTfulHandler)],
				      debug=True)

I'm saving the todos into GAE Datastore by using these structures (main.py):

class TodoList(db.Model):
    timestamp = db.DateTimeProperty(auto_now_add=True)

class Todos(db.Model):
    todolist = db.ReferenceProperty(TodoList)
    order = db.IntegerProperty()
    content = db.StringProperty()
    done = db.BooleanProperty()

A persistent cookie is set and the TodoList's key is used as the value. So the user can only access her todos and can view them in the future (main.py).

class MainHandler(webapp.RequestHandler):
    def get(self):
	if self.request.cookies.get('todos', None) == None:
	    todolist = TodoList()
	    todolist.put()
	    cookie = Cookie.SimpleCookie()
	    cookie['todos'] = todolist.key().__str__()
	    cookie['todos']['expires'] = datetime(2014, 1, 1).strftime('%a, %d %b %Y %H:%M:%S')
	    cookie['todos']['path'] = '/'
	    self.response.headers.add_header('Set-Cookie', cookie['todos'].OutputString())
	path = os.path.join(os.path.dirname(__file__), 'index.html')
	self.response.out.write(template.render(path, None))

Try the demo here: http://todolist-app.appspot.com/

Clone this wiki locally