Forums

Imported lists are empty

Hi,

I have some lists in one blueprint of my Flask project which I wish to import into another blueprint. When I create the lists and print them in the first blueprint (input_blueprint.py) it shows the following in the server log.

2021-03-17 15:20:13 INPUT_BLUEPRINT======INPUT TYPE========== ['image']
2021-03-17 15:20:13 INPUT_BLUEPRINT======INPUT title========== ['Exam']
2021-03-17 15:20:13 INPUT_BLUEPRINT======INPUT files========== [<FileStorage: 'Screenshot 2021-02-10 at 17.39.00.png' ('image/png')>]

However, when I import them from input_blueprint.py and print them in file_processing_blueprint.py, the list is empty (leading to 'IndexError: list index out of range' when I try to unpack an item from the list to use it). Server log:

2021-03-17 15:20:14 input title []
2021-03-17 15:20:14 files []
2021-03-17 15:20:14 INPUT_TYPE []

When I run the flask project locally everything works fine, but when I run it on Pythonanywhere the above occurs.

Are those prints coming from inside a function in input_blueprint.py? If they are then that may just be variables local to the function and not the global variables that you imported.

I have empty lists called input_title, input_type and input_files in the global scope of input_blueprint.py. Then, in a function, I append to these the input values of the form like this.

input_blueprint = Blueprint('input_blueprint', __name__) 
@input_blueprint.route('/', methods=['GET', 'POST']) #This is the homepage which will take the input
def index():
if request.method == 'POST': 
   input_title.append(request.form['title']) #INPUT TITLE APPEND
    input_type.append(request.form['file-type']) FILE TYPE APPEND
    files = request.files.getlist("file")      
    for file in files: #loops through each file uploaded, saves them in uploaded_files folder and appends the filename to input_files
        if file and allowed_file(file.filename):
            original_filename = secure_filename(input_title[0]) 
            unique_filename = make_unique(original_filename) #changed from original_filename
            title_w_unique_id.append(unique_filename) #Append title + unique number
            file.save(os.path.join('./Heiki_V1/uploaded_files/', unique_filename))
            input_files.append(url_for('input_blueprint.uploaded_file', filename=unique_filename)) #INPUT FILES APPEND
    return redirect('/process') 
return render_template("index.html")

Here is an introduction to Python variable scopes so you can understand why that doesn't work: https://realpython.com/python-scope-legb-rule/