简体   繁体   中英

passing a filename as a parameter from a for loop in python flask

I am uploading file so i am trying to pass a filename after looping through but i am getting an unbountLocalerror . i have tried making the filename global so that it can be seen outside the for loop but its throwing filename not defined. what other way can i use to get the filename so i can use it in html/jinja

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

    target = os.path.join(APP_ROOT,'static/')
    if not os.path.isdir(target):
        os.mkdir(target)
    else:
        for upload in request.files.getlist('file'):
            filename = upload.filename
            destination = "/".join([target, filename])
            upload.save(destination)
    return render_template("upload.html",filename=filename)
  • The error occurred because you created the local variable inside the else: statment.
  • If the for example the condition was that it triggered the if: part of the code the local variable filename would never be created.
  • Therefor the unbound error occurred when you tried to access it in return render_template("upload.html",filename=filename) .
  • IT also seems that you wanted to return multiple renders - because you don't have just one filename but bunch of them.
  • I changed teh function to return the list of render_template objects created based on filenames list that is being appended on line 10 ( filenames.append(upload.filename) ).

Code:

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

    target = os.path.join(APP_ROOT,'static/')
    if not os.path.isdir(target): #Create the target folder if it doesnt exitst
        os.mkdir(target)

    filenames = []
    for upload in request.files.getlist('file'): #Upload files into the folder
        filenames.append(upload.filename)
        destination = "/".join([target, upload.filename])
        upload.save(destination)

    return [render_template("upload.html",filename = filename) for filename in filenames] #Return therender_template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM