Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

JSON api

  • Loading branch information...
commit b060b485a267937565b49d15db90f3b68c6257a0 1 parent ea3be44
@anandology anandology authored
Showing with 28 additions and 1 deletion.
  1. +25 −0 utils.py
  2. +3 −1 webapp.py
View
25 utils.py
@@ -0,0 +1,25 @@
+import web
+import simplejson
+
+def json_processor():
+ if web.ctx.path.endswith('.json'):
+ web.ctx.path = web.ctx.path[:-len(".json")]
+ web.ctx.is_json = True
+ else:
+ web.ctx.is_json = False
+
+class Render(web.template.Render):
+ """JSON API aware render."""
+ def __init__(self, root, base=None):
+ web.template.Render.__init__(self, root, base=base)
+
+ def __getattr__(self, name):
+ if web.ctx.is_json:
+ return self.to_json
+ else:
+ return web.template.Render.__getattr__(self, name)
+
+ def to_json(self, d):
+ web.header('Content-Type', 'application/json')
+ return simplejson.dumps(d)
+
View
4 webapp.py
@@ -1,5 +1,6 @@
import web
+import utils
import db
urls = (
@@ -11,7 +12,8 @@
)
app = web.application(urls, globals())
-render = web.template.render("templates", base="layout")
+app.add_processor(web.loadhook(utils.json_processor))
+render = utils.Render("templates", base="layout")
class home:
def GET(self):
Please sign in to comment.
Something went wrong with that request. Please try again.