cherrypy用一个函数或类处理所有请求

2024-06-17 08:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用cherrypy,但我不想使用普通的调度程序,我希望有一个函数可以捕捉所有请求,然后执行我的代码。我认为我必须实现我自己的调度器,但我找不到任何有效的例子。你能帮我发布一些代码或链接吗?在

谢谢


Tags: 函数代码程序链接调度例子cherrypy
3条回答

您所要求的可以通过路由和定义自定义调度器来完成

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()}}

希望有帮助:)

设置默认函数:

import cherrypy

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

cherrypy.quickstart(server())

下面是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)

然后在配置中为您想要的路径设置它:

^{pr2}$

…其中“dispatch_func”是“捕捉所有请求的函数”。它将以位置参数的形式传递任何路径段,并将任何querystring作为关键字参数传递。在

相关问题 更多 >