在Flask路线中使用变量 [英] Using variables across Flask routes
问题描述
我正在学习Flask并有一个关于在路由上下文中使用变量的问题,例如我的app.py:
< pre class = lang-py prettyprint-override>
从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)
如果__name__ == __main__:
app.run()
在路线/ d下,如果变量d是通过获取已经计算的c和a的值来计算的,那么如何共享变量c以及页面之间的a,这样变量d就会被计算并呈现到dif.html?
谢谢
如果您不想使用
该错误表明 data.a
和当 processes = 10
时, data.c
保持无
。
因此,这证明我们不应该在Web应用程序中使用全局变量。
我们可以使用
< img src = https://i.stack.imgur.com/s3VxV.png alt = dif>
I am learning Flask and have a question regarding use of variables in the context of routes.For Example, my 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()
Under the route /dif the variable d is calculated by taking the values of already calculated c and a.How to share variables c and a between pages, so that variable d is calculated and rendered to dif.html?
Thank You
If you do not want to use Sessions one way to store data across routes is (See the update below):
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)
N.B.: It requires to visit /index
before visiting /dif
.
Update
Based on the davidism's comment the above code is not production friendly because it is not thread safe. I have tested the code with processes=10
and got the following error in /dif
:
The error shows that value of data.a
and data.c
remains None
when processes=10
.
So, it proves that we should not use global variables in web applications.
We may use Sessions or Database instead of global variables.
In this simple scenario we can use sessions to achieve our desired outcome. Updated code using sessions:
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)
Output:
这篇关于在Flask路线中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!