【问题标题】:Cherrypy Custom Dispatcher with Static Files带有静态文件的 Cherrypy 自定义调度程序
【发布时间】:2012-01-01 18:13:09
【问题描述】:

我已经编写了自己的自定义调度程序,它使用正则表达式来映射路由,但是,我不能再在 /static 中托管静态文件。这是调度程序和配置:

class Dispatcher(object):
def __init__(self):
    self.urls = {}

def __call__(self, path_info):
    print('Dispatcher called: ' + path_info)

    func = self.find_handler(path_info)
    cherrypy.serving.request.handler = func

def find_handler(self, path_info):
    request = cherrypy.serving.request
    request.config = cherrypy.config.copy()

    for url in self.urls:
        args = re.findall(url, path_info)

        if len(args) > 0:
            # in the case that the route is just a URL, we don't want
            # an extra argument in the method function
            try:
                args.remove(path_info)
            except ValueError:
                pass

            controller = self.urls[url]
            method = request.method.lower()

            return cherrypy._cpdispatch.LateParamPageHandler(getattr(controller, method), *args)

    return cherrypy.NotFound()

def connect(self, url, controller):
    if not url.endswith("$"):
        url += "$"

    self.urls[url] = controller

还有配置:

config = {
        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': port,
        },

        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.join(os.getcwd(), 'static'),
        },

        '/': {
            'request.dispatch': self.dispatcher,
        }
    }

如果我使用标准调度程序,静态文件可以正常工作,但是如果我使用自己的,它们将不再工作。在调度程序中完成调试后,静态文件将通过调度程序,即使我明确指出只有在 '/' 中才会使用调度程序。

【问题讨论】:

    标签: python regex static dispatcher cherrypy


    【解决方案1】:

    我不熟悉cherrypy,但似乎很明显:/static 中的所有内容也在/ 中,因此任何人都可以猜测它将使用哪个配置条目。我希望“更具体优先”,但根据您的描述,情况并非如此。查看文档也无济于事,没有提到模糊路径处理。

    您会认为更改顺序可能会有所帮助,但由于这是字典,因此不会保留顺序。

    Cherrypy 似乎无法做到这一点。如果它有一个默认调度程序与其他调度程序过载,则可以解决问题。另一种选择是您的自定义调度程序可以在检测到路径时调用静态调度程序。

    最后,文档讨论了“将应用程序安装到路径”。如果您这样做,您可能需要更改顺序。如果您不这样做,它可能会自动完成,手动执行可能会解决您的问题。

    并非所有这些都有意义,因为正如我所写,我对cherrypy并不熟悉,但我希望它对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多