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

发布于 2024-11-19 16:28:44 字数 118 浏览 2 评论 0原文

我想使用cherrypy,但我不想使用普通的调度程序,我想要一个函数来捕获所有请求,然后执行我的代码。我认为我必须实现自己的调度程序,但我找不到任何有效的示例。您可以通过发布一些代码或链接来帮助我吗?

谢谢

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. 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

零崎曲识 2024-11-26 16:28:44

创建一个默认函数:

import cherrypy

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

cherrypy.quickstart(server())

make a default function:

import cherrypy

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

cherrypy.quickstart(server())
一萌ing 2024-11-26 16:28:44

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

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

希望有帮助:)

What you ask can be done with routes and defining a custom dispatcher

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. 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 : )

许一世地老天荒 2024-11-26 16:28:44

这是 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”是您的“捕获所有请求的函数”。它将传递任何路径段作为位置参数,并将任何查询字符串作为关键字参数传递。

Here's a quick example for 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". It will be passed any path segments as positional arguments, and any querystring as keyword arguments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文