Created
September 19, 2012 20:15
-
-
Save teeler/3751961 to your computer and use it in GitHub Desktop.
Simple backbone.js handler for GAE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import logging | |
from google.appengine.ext import db | |
from google.appengine.api import users | |
import webapp2 | |
# With routes like: | |
#app = webapp2.WSGIApplication([ | |
# webapp2.Route("/d/<collection>", DataHandler, methods=["GET", "POST"]), | |
# webapp2.Route("/d/<collection>/<id>", DataHandler, methods=["GET", "PUT", "DELETE"]), | |
# | |
# This handler implements the simplest possible backbone handler for whatever data you like. | |
class Collection(db.Expando): | |
name = db.StringProperty() | |
class DataHandler(webapp2.RequestHandler): | |
def get(self, collection, id=None): | |
if id: | |
c = Collection.get_by_id(int(id)) | |
if c: | |
d = json.loads(c.data) | |
d["id"] = c.key().id() | |
self.response.out.write(json.dumps(d)) | |
else: | |
c = Collection.all() | |
self.response.out.write("[") | |
for rec in c.run(): | |
d = json.loads(rec.data) | |
d["id"] = rec.key().id() | |
self.response.out.write(json.dumps(d) + ",") | |
self.response.out.write("]") | |
def post(self, collection): | |
data = json.loads(self.request.body) | |
c = Collection(name = collection, | |
data = self.request.body) | |
c.put() | |
data["id"] = c.key().id() | |
self.response.out.write(json.dumps(data)) | |
def put(self, collection, id): | |
c = Collection.get_by_id(int(id)) | |
if c: | |
data = json.loads(self.request.body) | |
if data: | |
c.data = self.request.body | |
c.put() | |
self.response.out.write(json.dumps(data)) | |
def delete(self, collection, id): | |
c = Collection.get_by_id(int(id)) | |
if c: | |
c.delete() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment