webpy: How to serve JSON

为君一笑 提交于 2019-11-28 17:55:42

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)

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())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!