Forums

Flask app with global variables issue

Hi there,

I was wondering if anyone could help me out with this. I'm noticing a difference between Flask deals with global variables on PythonAnywhere initialized inside of if name == "main": compared with my local version.

e.g. the following will not work on PythonAnywhere but works locally i.e. my_list when sent to index.html will be empty.

from flask import Flask, render_template
app = Flask(__name__)
my_list = []

@app.route("/index")
def render_foo():
    return render_template("index.html", my_list=my_list)

if __name__ == "__main__":
    global my_list
    my_list.append(0)
    my_list.append(1)
    app.run()

If I change it to the following it works:

@app.route("/index")
def render_foo():
    global my_list
    my_list.append(0)
    my_list.append(1)
    return render_template("index.html", my_list=my_list)

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

Thanks in advance for the help.

Hi! It's not to do with global variables. It's because, on PythonAnywhere, we import your code, we don't run it directly, so we don't execute anything inside the __name__ = __main__ clause. and that's a good thing, because calling app.run() on pythonanywhere would be bad

Ah, makes sense. Is there a recommended place where I can put code that only needs to be run once on start up.

Thanks!

You could put it in your wsgi file (linked to from the web tab) -- but be aware that it will be run once for each web worker -- free users have 1 worker, but paying users have multiple worker processes, and each one will execute that code when they start up (or any time you hit the reload web app button)...

Thanks, that solved my problems.

:)