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

5 投票
3 回答
5244 浏览
提问于 2025-04-16 21:18

我想用cherrypy这个框架,但我不想用它默认的请求处理方式。我想要一个函数,可以接收所有的请求,然后执行我的代码。我觉得我需要自己实现一个请求处理器,但我找不到任何有效的例子。你能帮我发一些代码或者链接吗?

谢谢!

3 个回答

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”就是你用来处理所有请求的“函数”。它会把路径中的每一部分作为位置参数传给你,同时把查询字符串中的内容作为关键字参数传给你。

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

希望这能帮到你 : )

13

创建一个默认函数:

import cherrypy

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

cherrypy.quickstart(server())

撰写回答