如何在CKAN中制作定制的中间件

时间:2018-09-07 23:02:44

标签: python flask middleware pylons ckan

我遇到了一个方案,我必须重写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)方法,该方法在配置阶段调用environ时会传入start_responsemake_pylons_stack。如果要覆盖TrackingMiddleware,是否应该在config/middleware/myTrackingMiddleware.py下创建另一个ckanext-myext/,然后在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,但是我没有收到'/_tracking'中对myTrackingMiddleware的任何请求。

1 个答案:

答案 0 :(得分:1)

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