python - 在运行时更改蓝图或重新加载 flask 应用程序

标签 python flask

我正在编写一个支持插件架构的 Flask 应用程序。每个插件都位于一个单独的文件夹中,并且是一个模块,该模块至少有一个类是 Plugin 类的子类。出于安全原因,我不想在最初运行 Flask 应用程序时加载所有插件。相反,用户可以从 Flask 应用程序中启用插件。一旦他这样做了,我们就会在数据库中存储一份备忘录,将要加载的应用程序列入白名单。但是,我们仍然要记住禁用了哪些插件,并为这些插件证明了 View 。为此,我为未启用且不加载任何自定义代码的插件创建了一个虚拟类。

每个插件都有自己的蓝图。我们在加载插件时注册它。蓝图还定义了启用插件的路径。 整个事情看起来像这样:

for plugin_name in os.listdir(plugin_dir):
    plugin_path = os.path.join(plugin_paths, plugin_name)
    module_name = "plugins.{}.__init__".format(plugin_name)
    plugin_enabled = ask_db_whether_plugin_is_enabled(plugin_name)

    if os.path.isdir(plugin_path) and plugin_enabled:
        module = __import__(module_name)
        for plugin in load_plugins_from_module(module):
            app.register_blueprint(plugin.blueprint, url_prefix='/plugins')
    else:
        PluginCls = type(identifier, (Plugin, ), {})
        disabled_plugin = PluginCls()
        app.register_blueprint(disabled_plugin.blueprint, url_prefix='/plugins')

load_plugins_from_module 看起来像这样:

def load_plugins_from_module(module):
    def is_plugin(c):
        return inspect.isclass(c) and \
               issubclass(c, Plugin) and \
               c != Plugin

    for name, objects in inspect.getmembers(module, lambda c: inspect.ismodule(c)):
        for name, PluginCls in inspect.getmembers(objects, is_plugin):
            plugin = PluginCls()
            yield plugin

现在的问题是:当我将插件更改为已启用时,我基本上想重新运行

module = __import__(module_name)
for plugin in load_plugins_from_module(module):
    app.register_blueprint(plugin.blueprint, url_prefix='/plugins')

用于该插件的模块,以便它变为事件状态并注册所有已在子类插件中定义的路由。这将引发 AssertionError,因为我无法在运行时更改蓝图。什么是一个好的解决方法?我可以从应用程序中重新加载应用程序吗?我可以在运行时修改现有的蓝图吗?

感谢您的帮助!

最佳答案

我不确定您是否需要弄得这么复杂。

您可以简单地为您想要启用的插件设置配置选项。您可以在“Start_app()”方法中根据该配置注册您的蓝图。

您还可以动态设置配置选项以从某些文件夹/文件继承,例如使其更具动态性。

插件通常由开发人员提供,因此配置选项并不麻烦,除非您尝试构建让每个随机用户都可以修改您的网站的东西——这可能会带来巨大的安全问题。

For security reasons, I don't want to load all the plugins when the flask app is initially run.

我不确定。不允许用户手动启动插件,会带来更大的安全风险(因此,如果用户能够 secret 上传代码,那么他现在就可以启用它们)。

您可以制作一个像 WordPress 一样启用插件的 CMS,只需在用户单击“激活插件”之前不路由插件的 URL

关于python - 在运行时更改蓝图或重新加载 flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16016060/

相关文章:

python - 如何不在 django 中只缓存模板的一段代码

Python Flask - 使用装饰器设置 cookie

python - 动态添加基类?

python - 安装时构建 conda 包

python - 创建距中心距离的列

python - 在线程中使用 Popen 会阻塞每个传入的 Flask-SocketIO 请求

python - AJAX POST Flask WTForm 不刷新页面

python - 不同的 :maxdepth: for specific entries in toctree (Sphinx)

python - 如何在 python flask sqlalchemy marshmallow 应用程序中将一个属性对象数组渲染为平面数组?

python - Flask-Admin:同时在两个表中插入数据