2011-07-11 28 views
4

我想使用cherrypy,但我不想使用正常的调度,我想有一个函数,捕获所有的请求,然后执行我的代码。我认为我必须实现我自己的调度员,但我找不到任何有效的示例。你能通过发布一些代码或链接来帮助我吗?cherrypy处理所有的请求与一个功能或类

感谢

回答

2

什么你问能不能与路线进行,并定义自定义调度

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

类似于下面的东西。请注意分配给用作所有路由控制器的变量的类实例,否则您将获得您的类的多个实例。这与链接中的例子不同,但我认为更多的是你想要的。

class Root: 
    def index(self): 
     <cherrpy stuff> 
     return some_variable 

dispatcher = None 
root = Root() 

def setup_routes(): 
    d = cherrypy.dispatch.RoutesDispatcher() 
    d.connect('blog', 'myblog/:entry_id/:action', controller=root) 
    d.connect('main', ':action', controller=root) 
    dispatcher = d 
    return dispatcher 

conf = {'/': {'request.dispatch': setup_routes()}} 

希望有所帮助:)

+0

我错了或该解决方案假设我已经知道了所有可用的路径时CherryPy的开始?这不是我的情况,我不得不每次查询数据库以查找特定url是否有效以及要显示的内容 – wezzy

+0

是的,它确实假定您已经知道您所服务的路径。如果您在数据库中有这些路径,则可以在调度函数中的应用程序启动时构建路径。很难在不知道更多的情况下为您提供完整的解决方案,但您应该能够遍历游标并将所有路径指向实例化的类。希望你的路径不是动态的。此解决方案需要重新启动应用程序才能更改每个路径。 – fellyn

1

下面是CherryPy的3.2一个简单的例子:

from cherrypy._cpdispatch import LateParamPageHandler 

class SingletonDispatcher(object): 

    def __init__(self, func): 
     self.func = func 

    def set_config(self, path_info): 
     # Get config for the root object/path. 
     request = cherrypy.serving.request 
     request.config = base = cherrypy.config.copy() 
     curpath = "" 

     def merge(nodeconf): 
      if 'tools.staticdir.dir' in nodeconf: 
       nodeconf['tools.staticdir.section'] = curpath or "/" 
      base.update(nodeconf) 

     # Mix in values from app.config. 
     app = request.app 
     if "/" in app.config: 
      merge(app.config["/"]) 

     for segment in path_info.split("/")[:-1]: 
      curpath = "/".join((curpath, segment)) 
      if curpath in app.config: 
       merge(app.config[curpath]) 

    def __call__(self, path_info): 
     """Set handler and config for the current request.""" 
     self.set_config(path_info) 

     # Decode any leftover %2F in the virtual_path atoms. 
     vpath = [x.replace("%2F", "/") for x in path_info.split("/") if x] 
     cherrypy.request.handler = LateParamPageHandler(self.func, *vpath) 

然后,只需将它设置在配置的路径,你打算:

[/single] 
request.dispatch = myapp.SingletonDispatcher(myapp.dispatch_func) 

...其中“dispatch_func”是您的“捕获所有请求的功能”。它将传递任何路径段作为位置参数,并将任何查询字符串作为关键字参数传递。

+1

嗯,但不会为每个URI的应用程序收集配置。明天我会看看能否改善上述情况。 – fumanchu

+0

确定修复.......... – fumanchu

+0

呃也许我太新手了,但我无法让你的例子工作,看到这个https://gist.github.com/1086473如果我打电话给127.0.0.1 :8080我得到了“hello world”的消息,但我想要的是处理其他url,我无法确定在启动和测试()函数永远不会被调用。是否有可能捕获404例外来处理所有路径? – wezzy

11

使默认功能:

import cherrypy 

class server(object): 
     @cherrypy.expose 
     def default(self,*args,**kwargs): 
       return "It works!" 

cherrypy.quickstart(server()) 
+0

工作正常!并帮助我。 –

相关问题