Forums

Issue with global variables in Flask app

Hello, I have a strange issue in my flask app, that currently prints this error in the logs:

2017-11-17 15:34:35,140: Error running WSGI application
2017-11-17 15:34:35,140:   File "/home/Fragoel2/afp-mapping-site/flask_app.py", line 69
2017-11-17 15:34:35,141: 
2017-11-17 15:34:35,141:     global feature_list
2017-11-17 15:34:35,141: 
2017-11-17 15:34:35,141: SyntaxError: name 'feature_list' is used prior to global declaration
2017-11-17 15:34:35,141:   File "/var/www/fragoel2_pythonanywhere_com_wsgi.py", line 16, in <module>
2017-11-17 15:34:35,141:     from flask_app import app as application
2017-11-17 15:34:35,141: ***************************************************
2017-11-17 15:34:35,141: If you're seeing an import error and don't know why,
2017-11-17 15:34:35,142: we have a dedicated help page to help you debug: 
2017-11-17 15:34:35,142: https://help.pythonanywhere.com/pages/DebuggingImportError/
2017-11-17 15:34:35,142: ***************************************************

In my code first thing I do is init some global variables:

app = Flask(__name__)
feature_list = []
feature_count = 1

Then in my code I have:

First access to page
if request.method == 'GET':
    reset_globals()

# Handle case in which we need to add a field to form
if request.method == 'POST' and request.form['submit'] == 'Add new row':
    global feature_count, feature_list
    feature_count += 1
    feature_list.append(feature_count)

# Handle case in which we need to remove a field to form
if request.method == 'POST' and request.form['submit'].startswith('Delete row '):
    removal_id = int(request.form['submit'][-1]) - 1
    global feature_count, feature_list
    feature_list.pop(removal_id)
    MappingForm.delete_form_field_dinamically(removal_id)

# Utility function to reset global variables
def reset_globals():
     global feature_list, feature_count
     feature_count = 0
     feature_list = [feature_count]

Weird thing is, my code runs fine locally on my machine but fails when hosted on Pythonanywhere... any clue why?

Are all of those ifs in the same method? If they are, then the error is correct - you're using feature_list in the first one before the global declaration in the second one. I have no idea how that might be working locally.

Yes, those are all from the same method, but I also initialize the variables before any method declaration (look at the first code block)

looking at the initial error traceback, it errors on the line "global feature_list".

Have you looked to see if that line (ie. at "/home/Fragoel2/afp-mapping-site/flask_app.py", line 69) is called before your global variables are instantiated?