2011-07-11 29 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

工作正常!並幫助我。 –

相關問題