-4

I have a problem with the global variable in Flask.

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def define_x():
    global x
    x = 10
    return redirect('/test')

@app.route('/test')
def test_x():
    return str(x)

if __name__ == '__main__':
    app.run()

There is an error when url redirect:

NameError: global name 'x' is not defined

But if I define 'x' on the top of the function:

from flask import Flask, redirect

app = Flask(__name__)
x = None

@app.route('/')
def define_x():
    global x
    x = 10
    return redirect('/test')

@app.route('/test')
def test_x():
    return str(x)

if __name__ == '__main__':
    app.run()

the redirect page return None not 10.

ElChiang
  • 7
  • 3
  • x is defined within the function and cannot be accessed outside of it unless already defined before it (which is suggested in another duplicate question...) – L_Church Apr 17 '18 at 09:17
  • 2
    Note that **you cannot and must not** try to use global variables to store state between requests. Like any web framework, Flask is a multi-user system and globals will be shared by all users. – Daniel Roseman Apr 17 '18 at 09:19
  • @DanielRoseman that's not the reason. The reason is some wsgi containers will run the app in different processes and what not. Depending on what you're trying to do globals could work fine. But even then, it's still horrible from a maintainability point of view. – vidstige Apr 17 '18 at 10:00

1 Answers1

1

Just add

x = None

at top of script

vidstige
  • 12,492
  • 9
  • 66
  • 110
  • I tried to declare x at the top of the function, but if I add `x = None`, the redirect page return None not 10 – ElChiang Apr 17 '18 at 09:24
  • read my answer again. Does it say "top of function" or "top of script"? – vidstige Apr 17 '18 at 09:39
  • I was wrong about the last comment, but I do add `x = None` at the top of the script, it still returns `None` after redirection... – ElChiang Apr 17 '18 at 10:04
  • Ok, but the question was about "NameError: global name 'x' is not defined". Do you have another question? – vidstige Apr 17 '18 at 10:20