0

I am trying to use a global variable within my flask app:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

varGlobal = None
@app.route('/')
def home():
    return render_template('home.html')

@app.route('/api/prepare', methods=['POST'])
def prepare():

    if varGlobal is None:
       varGlobal = "some_val"
    return varGlobal

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8989, debug=True)

So when my page loads and I hit api/prepare I get:

UnboundLocalError: local variable 'varGlobal' referenced before assignment

I want this varGlobal to persist as long as my app is running. Even if I reload the page. How can I do this?

Payden K. Pringle
  • 61
  • 1
  • 2
  • 19
AbtPst
  • 7,778
  • 17
  • 91
  • 172
  • 1
    add a line "global varGlobal" just under the prepare function definition – NendoTaka Nov 14 '17 at 21:53
  • 3
    You assign to the `varGlobal` in `prepare`. So it is **not** a global variable. Use `global varGlobal` as first line in `prepare`. That being said, global variables are usually **not** a good idea. – Willem Van Onsem Nov 14 '17 at 21:55
  • 2
    Note, you almost certainly don't want to do this anyway, as it won't work properly in production. – Daniel Roseman Nov 14 '17 at 22:01

1 Answers1

0

I won't mention again the reason of your traceback, that's mainly because you're not using the global keyword so the global variable can't be bound properly from your method as other already clarified in the comments/answers.

Now, I'd strongly recommend you to avoid global variables, specially in multithread environments, they are evil. Your code will fail miserably when different threads are being spawned (ie: multiple users).

Instead, i'd suggest you get familiar with some of the flask utils created for this very specific task, like this one http://flask.pocoo.org/docs/0.12/api/#flask.Flask.app_ctx_globals_class.

BPL
  • 9,632
  • 9
  • 59
  • 117