webpy: How to serve JSON webpy: How to serve JSON python python

webpy: How to serve JSON


I wouldn't think you'd have to do any thing overly "special" for web.py to serve JSON.

import webimport jsonclass index:    def GET(self):        pyDict = {'one':1,'two':2}        web.header('Content-Type', 'application/json')        return json.dumps(pyDict)


It is certainly possible to serve JSON from webpy, But if you and choosing a framework, I would look at starlight and my fork twilight (for documentation).

It has a JSON wrapper for fixing the http headers for your json response.

it uses either the json or simplejson libraries for json handling the conversions to and from other objects.

I am using it right now and it is great.

https://bitbucket.org/marchon/twilight

in it you will find an example called ShowMeTheJson.py

that uses simple json

from starlight import *from werkzeug.routing import Mapfrom werkzeug.routing import RuleFactoryimport simplejsonclass ShowMeTheResponses(App):######################################################################   Sample URLS to Test Responses ##   http://localhost:8080/                root##   http://localhost:8080/json            return JSON Mime Type Doc  ####################################################################   @default   def hello(self):       return 'Hello, world!'   @dispatch('/')   def index(self):        return 'Hello Root!'   @dispatch('/html')   def indexhtml(self):        return HTML('Hello HTML')   @dispatch('/json')   def indexjson(self):       directions = {'N' : 'North', 'S' : 'South', 'E':'East', 'W' : 'West'}       return JSON(simplejson.dumps(directions))         if __name__ == '__main__':    from werkzeug import run_simple    run_simple('localhost', 8080, ShowMeTheResponses())