简体   繁体   English

cherrypy 使用一个 function 或 class 处理所有请求

[英]cherrypy handle all request with one function or class

i'd like to use cherrypy but i don't want to use the normal dispatcher, i'd like to have a function that catch all the requests and then perform my code.我想使用cherrypy,但我不想使用普通的调度程序,我想要一个function 来捕获所有请求然后执行我的代码。 I think that i have to implement my own dispatcher but i can't find any valid example.我认为我必须实现自己的调度程序,但我找不到任何有效的例子。 Can you help me by posting some code or link?您可以通过发布一些代码或链接来帮助我吗?

Thanks谢谢

make a default function:设置默认 function:

import cherrypy

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

cherrypy.quickstart(server())

What you ask can be done with routes and defining a custom dispatcher您可以通过路由和定义自定义调度程序来完成您的要求

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

Something like the following.类似于以下内容。 Note the class instantiation assigned to a variable that is used as the controller for all routes, otherwise you will get multiple instances of your class.注意 class 实例化分配给一个变量,该变量用作所有路由的 controller,否则您将获得 class 的多个实例。 This differs from the example in the link, but I think is more what you want.这与链接中的示例不同,但我认为更多的是您想要的。

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

Hope that helps: )希望有帮助:)

Here's a quick example for CherryPy 3.2:这是 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)

Then just set it in config for the paths you intend:然后只需在配置中为您想要的路径设置它:

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

...where "dispatch_func" is your "function that catches all the requests". ...其中“dispatch_func”是您的“捕获所有请求的函数”。 It will be passed any path segments as positional arguments, and any querystring as keyword arguments.它将作为位置 arguments 传递任何路径段,并将任何查询字符串作为关键字 arguments 传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM