在应用工厂中创建 Flask 扩展时导入 [英] Import Flask extension when it is created in an app factory

查看:27
本文介绍了在应用工厂中创建 Flask 扩展时导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序的不同模块中使用 Flask-Perm 的装饰器.我正在使用应用程序工厂模式.如果我在工厂中创建扩展,则无法将其导入以在其他模块中使用.使用应用工厂时如何导入扩展程序?

I want to use Flask-Perm's decorators in different modules in my application. I am using the app factory pattern. If I create the extension in the factory, I can't import it to use in the other modules. How can I import an extension when using an app factory?

from flask_perm import Perm

def create_app():
    app = Flask(__name__)
    perm = Perm(app)
    return app

推荐答案

Flask-Perm 的 docs 在顶部显示如何执行此操作.

Flask-Perm's docs show how to do this right at the top.

在工厂外创建扩展.在工厂内部初始化扩展.每个支持应用工厂的 Flask 扩展都使用这种模式.

Create the extension outside the factory. Init the extension inside the factory. Every Flask extension that supports app factories uses this pattern.

perm = Perm()

def create_app():
    app = Flask(__name__)
    perm.init_app(app)
    return app

现在您可以在任何需要访问它的地方使用 from myproject import perm.

Now you can use from myproject import perm wherever you need to access it.

这篇关于在应用工厂中创建 Flask 扩展时导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆