Using variables across Flask routes [duplicate]

2019-06-01 04:03发布

问题:

This question already has an answer here:

  • Are global variables thread safe in flask? How do I share data between requests? 2 answers

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

回答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__)

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:



回答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")
    def index():

       a=3
       b=4
       c=a+b

    return render_template('index.html',c=c)

    @app.route("<variable1>/dif/<variable2>")
    def dif(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>