Search code examples
pythonamazon-web-servicesflaskglobal-variables

How can I access a variable globally in flask


I am trying to save a variable globally and access it in other parts of my app it works on my local server but it returns a TOKEN not defined error in production

@app.route("/", methods=['POST', 'GET'])
def get_data():
   global Token
    if request.method == 'POST':
        token = request.form["x-token"]
        if is_valid(token):

            Token = token
            return render_template("index.html")

@app.route("/signip", methods=["POST"])
def save_data():
  customer_data = marketplace.resolve_customer(RegistrationToken=Token)

What can I do to make this Token globally accessible


Solution

  • In Flask you have g (read about it and you will know), that can be used to set global variable. But its based on requests. At every requests, g will be reset. User defined global token variable will also do the same.

    So if you want something global between the requests, then one solution (though I am not an expert and do not know whether it is elegant or not, there might be better elegant solutions) is to use session variable. So if you store in the session dict, it will be available during the entire session regardless of how many requests are being sent from your templates.

    Hope this resolves your issue.