本文介绍了cherrypy-URL调度程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将URL regEx(例如/data/[A-Z].txt)映射到cherrypy中的资源?那里有一个简单的例子吗?我在这里没有文档.

How would I map a url regEx such as /data/[A-Z].txt to a resource in cherrypy? Is there an simple example somewhere? I don't get the docs here.

http://tools.cherrypy.org/wiki/RestfulDispatch

推荐答案

您可以使用 RoutesDispatcher

import cherrypy

class City:
    def __init__(self, name):
        self.name = name
        self.population = 10000

    @cherrypy.expose
    def index(self, **kwargs):
        return "Welcome to %s, pop. %s" % (self.name, self.population)

    @cherrypy.expose
    def update(self, **kwargs):
        self.population = kwargs['pop']
        return "OK"

d = cherrypy.dispatch.RoutesDispatcher()
d.connect(action='index', name='hounslow', route='/hounslow', controller=City('Hounslow'))
d.connect(action='index', name='surbiton', route='/surbiton', controller=City('Surbiton'),
          conditions=dict(method=['GET']))
d.mapper.connect('/surbiton', controller='surbiton',
                 action='update', conditions=dict(method=['POST']))

conf = {'/': {'request.dispatch': d}}
cherrypy.config.update({'server.socket_port': 5000})
cherrypy.tree.mount(root=None, config=conf)
cherrypy.engine.start()

您可以在 http://127.0.0.1:5000/surbiton 上使用浏览器进行测试您可以使用curl测试POST命令:

You might test this with a browser on http://127.0.0.1:5000/surbiton You can test the POST command with curl:

curl -i -X GET http://127.0.0.1:5000/surbiton
curl -i -d "pop=100" -X POST http://127.0.0.1:5000/surbiton
curl -i -X GET http://127.0.0.1:5000/surbiton

其中有 Routes项目中的文档.

或者来自 appmecha 的示例.

这篇关于cherrypy-URL调度程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:00