嗯,AJAX 调用需要从某处的服务器中提取数据。如果目标是避免服务器端的复杂设置,CherryPy 可以保持服务器端代码非常小。
我在下面写了一个简单的例子。第一类是放置 ReST API 逻辑的地方。类下面的代码是启动和运行服务器所需的全部内容。
安装 Python 2.6,将下面的代码保存到 restExample.py。然后在您的命令行中通过执行“python restExample.py”运行 python 文件。将您的浏览器指向http://localhost:8080/blog/999,然后查看返回的一些 JSON。
import cherrypy
import json
# Create the controller
class Blog_Controller(object):
def get(self, entryID):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
# Update DB with passed in arguments. entryID comes from URL,
# other two entries come from POST
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'success':True})
# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
controller=Blog_Controller(),
conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
controller=Blog_Controller(),
conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)
# Start the webserver
engine = cherrypy.engine
try:
engine.start()
except:
sys.exit(1)
else:
engine.block()