Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

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)
question from:https://stackoverflow.com/questions/65876267/passing-a-filename-as-a-parameter-from-a-for-loop-in-python-flask

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...