繁体   English   中英

将文件名作为参数从 python flask 中的 for 循环传递

[英]passing a filename as a parameter from a for loop in python flask

我正在上传文件,所以我试图在循环后传递一个文件名,但我得到一个unbountLocalerror 我尝试将文件名设为全局,以便在 for 循环之外可以看到它,但未定义其抛出的文件名。 我可以用什么其他方式来获取文件名,这样我就可以在 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)
  • 发生错误是因为您在 else: 语句中创建了局部变量。
  • 例如,如果条件是它触发了if:部分代码,则永远不会创建local variable文件名。
  • 因此,当您尝试在return render_template("upload.html",filename=filename)中访问它时发生unbound错误。
  • IT 似乎还想返回多个渲染 - 因为您不只有一个filename ,而是一堆文件名。
  • 我更改了 function 以返回根据第 10 行附加的filenames列表创建的render_template对象列表( filenames.append(upload.filename) )。

代码:

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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