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: