tags:

views:

227

answers:

2

Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages.

I try to look for answers in the documentation, but I'm not able to find anything.

Thanks, Giovanni

A: 

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 Map
from werkzeug.routing import RuleFactory

import simplejson


class 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())
George Lambert
it's great, but I cannot migrate all my website.do you have any pointer for webpy?
Giovanni Di Milia
+3  A: 

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

import web
import json

class index:
    def GET(self):
        pyDict = {'one':1,'two':2}
        web.header('Content-Type', 'application/json')
        return json.dumps(pyDict)
Mark
perfect! I knew it was simpler than I was imaging! thanks a lot!
Giovanni Di Milia