Jam*_*der 2 python routes jinja2 flask
我正在学习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()
Run Code Online (Sandbox Code Playgroud)
在路由/ dif下,变量d是通过获取已经计算出的c和a的值来计算的。如何在页面之间共享变量c和a,以便计算出变量d并将其呈现给dif.html?
谢谢
如果您不想使用会话,则一种跨路由存储数据的方法是(请参阅下面的更新):
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)
Run Code Online (Sandbox Code Playgroud)
注意:它需要先访问,/index然后再访问/dif。
根据大卫的评论,以上代码不友好,因为它不是线程安全的。我已经测试过代码,processes=10并在中出现以下错误/dif:
错误显示的该值data.a和data.c遗体None时processes=10。
因此,证明了我们不应在Web应用程序中使用全局变量。
我们可以使用会话或数据库代替全局变量。
在这种简单的情况下,我们可以使用会话来达到期望的结果。使用会话更新了代码:
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)
Run Code Online (Sandbox Code Playgroud)
输出: