Using Variables Across Flask Routes
Solution 1:
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__)
classDataStore():
a = None
c = None
data = DataStore()
@app.route("/index")defindex():
a=3
b=4
c=a+b
data.a=a
data.c=c
return render_template("index.html",c=c)
@app.route("/dif")defdif():
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")defindex():
a=3
b=4
c=a+b
session["a"]=a
session["c"]=c
return render_template("home.html",c=c)
@app.route("/dif")defdif():
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:
Solution 2:
You can use variables in flask using by writing the variable passed from HTML like this in your URL. ,
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/index")defindex():
a=3
b=4
c=a+b
return render_template('index.html',c=c)
@app.route("<variable1>/dif/<variable2>")defdif(variable1,variable2):
d=c+a
return render_template('dif.html',d=d)
if __name__ == "__main__":
Your html will be like: as form:
<form action="/{{ variable1 }}/index/{{ variable2}}" accept-charset="utf-8"class="simform" method="POST"
As href:
<a href="{{ url_for('index',variable1="variable1",variable2="variable2") }}"><span></span> link</a></li>
Post a Comment for "Using Variables Across Flask Routes"