访问蓝图应用程序中的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