【问题标题】:How to make customized middleware in CKAN如何在 CKAN 中制作定制的中间件
【发布时间】:2025-12-19 05:30:11
【问题描述】:

我遇到了一个场景,我必须覆盖 CKAN 中的一个通用中间件。而在CKAN默认plugins/interface.py

class IMiddleware(Interface):
    u'''Hook into CKAN middleware stack
    Note that methods on this interface will be called two times,
    one for the Pylons stack and one for the Flask stack (eventually
    there will be only the Flask stack).
    '''
    def make_middleware(self, app, config):
        u'''Return an app configured with this middleware
        When called on the Flask stack, this method will get the actual Flask
        app so plugins wanting to install Flask extensions can do it like
        this::
            import ckan.plugins as p
            from flask_mail import Mail
            class MyPlugin(p.SingletonPlugin):
                p.implements(p.I18nMiddleware)
                def make_middleware(app, config):
                    mail = Mail(app)
                    return app
        '''
        return app

这表明我必须在我想在扩展中实现的插件下定义“MyMiddleWare”类。但是,如示例中所示,实际的中间件 Mail 是从不同的类导入的。我想覆盖TrackingMiddleware 尤其是__call__(self, environ, start_response) 方法,在配置阶段调用make_pylons_stack 时会传入environstart_response。如果我想覆盖TrackingMiddleware 我应该在ckanext-myext/ 下创建另一个config/middleware/myTrackingMiddleware.py 然后在plugin.py 中实现以下内容吗?:

from myTrackingMiddleware import MyTrackingMiddleware

class MyPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IMiddleware, inherit=True)

    def make_middleware(self, app, config):
        tracking = MytrackingMiddleware(app, config)
        return app

更新:

我尝试在层次结构中创建myTrackingMiddleware 并将其导入plugin.py,但在myTrackingMiddleware 中我没有收到对'/_tracking' 的任何请求。

【问题讨论】:

    标签: python flask middleware pylons ckan


    【解决方案1】:

    我已经实现了一套流程,它适用于我自己。基本上,我保留了我在自己的问题中提到的内容。然后,如果您的中间件与 CKAN 默认中间件有冲突,您可能必须完全禁用默认中间件。我在这里与 CKAN 的一些主要贡献者进行了讨论:https://github.com/ckan/ckan/issues/4451。在我禁用 dev.ini 中的 CKAN ckan.tracking_enabled 后,我可以灵活地从 environ 获取值并使用我的自定义逻辑处理跟踪。

    【讨论】: