【问题标题】:Use flask variable outside of context在上下文之外使用烧瓶变量
【发布时间】:2020-11-30 11:22:31
【问题描述】:

在 Flask 应用程序中(在 __init__.py 中初始化)我有两个蓝图 - authmain 。在auth 蓝图中,我试图设置一些变量(将从数据库加载并依赖于current_user.get_id()),这些变量应该在main 蓝图中用作url-prefix:

auth.py

@auth.route('/login', methods=['POST'])
def login_post():
    username = request.form.get('username')
    password = request.form.get('password')

    user_inst = user.query.filter_by(username=username).first()


    if not user_inst or not check_password_hash(user_inst.password, password):
        flash('Invalid credentials. Check you input and try again.')
        return redirect(url_for('auth.login')) 

    login_user(user_inst)
    
    g.team_name = 'some_team_name'
    #session['team_name'] = 'some_team_name'
    
    # if the above check passes, then we know the user has the right credentials
    return redirect(url_for('main.some_func'))

在主蓝图中,需要获取team_name变量:

main = Blueprint('main', __name__, static_folder="static", static_url_path="", url_prefix=g.team_name)

您能否告知是否有适当的方法将变量从auth 导入到main(在其初始化之前)而无需获取:

RuntimeError: Working outside of application context.

【问题讨论】:

    标签: python flask blueprint


    【解决方案1】:

    您的问题的基本解决方法是在 app.app_context(): 中注册蓝图

    这似乎是你的第一个烧瓶项目,这是考虑项目结构的常见问题。阅读 Flask 应用工厂模式并应用它。

    your_app/__init__.py

    def create_app(app_config):
        app = Flask(__name__)
        with app.app_context():
            from your_app.somewhere import team_name
    
            app.register_blueprint(team_name)
        return app
    

    【讨论】:

    • 太棒了!非常感谢!
    • 另一个提示:在 github 开放存储库中搜索 flask create_app 并简单地复制项目设计))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多