访问蓝图应用程序中的Flask全局变量 [英] Access to Flask Global Variables in Blueprint Apps

查看:83
本文介绍了访问蓝图应用程序中的Flask全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的源代码具有以下结构:

my source code has this structure:

main.py :

from flask import Flask, g
app = Flask(__name__)
with app.app_context():
    g.my_db = PostgreSQL()
    app.register_blueprint(my_app, url_prefix="/my_app")

my_app.py :

from flask import Blueprint, g
my_app = Blueprint("my_app", __name__)
@my_app.route("/")
def index():
    return g.my_db.fetch_all()   <<< ERROR

但它显示此错误:

AttributeError:'_AppCtxGlobals'对象没有属性'my_db'

即使我尝试在应用程序上下文之外使用 g ,它也会显示此错误:

Even when I try to use g outside of app context, it shows this error:

RuntimeError:在应用程序上下文之外工作.

那么如何在Flask中设置和访问全局变量?

So how to set and access to global variables in Flask?

推荐答案

g 在您尝试使用它的方式上并不持久.编写一个函数,以在每次需要时创建连接.最好使用数据库扩展程序(例如Flask-SQLAlchemy)来为您管理连接.

g isn't persistent in the way you're trying to use it. Write a function to create a connection each time you need it. Preferably use a database extension like Flask-SQLAlchemy to manage connections for you.

db.py :

import <postgresql dependencies>

def get_db():
   db = PostgreSQL()
   # config here
   return db

main.py :

from flask import Flask

app = Flask(__name__)
app.register_blueprint(my_app, url_prefix="/my_app")

my_app.py :

from flask import Blueprint, g
from db import get_db

my_app = Blueprint("my_app", __name__)

@my_app.route("/")
def index():
    db = get_db()
    data = db.fetch_all()
    db.close()
    return data

这篇关于访问蓝图应用程序中的Flask全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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