我正在学习 Flask,并且有一个关于在路由上下文中使用变量的问题。例如,我的 app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/index")
def index():
a=3
b=4
c=a+b
return render_template('index.html',c=c)
@app.route("/dif")
def dif():
d=c+a
return render_template('dif.html',d=d)
if __name__ == "__main__":
app.run()
在/dif 路由下,变量d 是通过取已经计算好的c 和a 的值来计算的。如何在页面之间共享变量c 和a,以便计算变量d 并呈现到dif.html?
谢谢
如果你不想使用Sessions跨路线存储数据的一种方法是(请参阅下面的更新):
from flask import Flask, render_template
app = Flask(__name__)
class DataStore():
a = None
c = None
data = DataStore()
@app.route("/index")
def index():
a=3
b=4
c=a+b
data.a=a
data.c=c
return render_template("index.html",c=c)
@app.route("/dif")
def dif():
d=data.c+data.a
return render_template("dif.html",d=d)
if __name__ == "__main__":
app.run(debug=True)
注意:需要访问/index
参观前/dif
.
更新
根据 davidism 的评论,上面的代码对生产环境不友好,因为它不是线程安全的。我用 processes=10
测试了代码并在 /dif
中出现以下错误:
错误显示 data.a
的值和 data.c
遗迹 None
什么时候processes=10
.
因此,它证明我们不应该在网络应用程序中使用全局变量。
我们可以使用 Sessions或数据库而不是全局变量。
在这个简单的场景中,我们可以使用 session 来实现我们想要的结果。
使用 session 更新代码:
from flask import Flask, render_template, session
app = Flask(__name__)
# secret key is needed for session
app.secret_key = 'dljsaklqk24e21cjn!Ew@@dsa5'
@app.route("/index")
def index():
a=3
b=4
c=a+b
session["a"]=a
session["c"]=c
return render_template("home.html",c=c)
@app.route("/dif")
def dif():
d=session.get("a",None)+session.get("c",None)
return render_template("second.html",d=d)
if __name__ == "__main__":
app.run(processes=10,debug=True)
输出: