是否可以使用 webpy 来提供 JSON?我建立了我的网站,我需要以 JSON 格式提供一些信息,以便与某些页面上的 Javascript 进行交互。
我尝试在文档中寻找答案,但我找不到任何东西。
谢谢,乔瓦尼
我认为您不必为 web.py 做任何过于“特殊”的事情来提供 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)
当然可以从 webpy 提供 JSON,但是如果你选择一个框架,我会看看 starlight 和我的 fork twilight(用于文档)。
它有一个 JSON 包装器,用于修复 json 响应的 http 标头。
它使用 json 或 simplejson 库来处理与其他对象之间的转换。
我现在正在使用它,它很棒。
https://bitbucket.org/marchon/twilight
在其中您会找到一个名为 ShowMeTheJson.py 的示例
使用简单的 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())