request.files中的文件不为空如何实现

How to implement if file in request.files is not empty

我试图实现的逻辑:如果用户没有将文件上传到文件字段从而使其为空,则不要将文件上传到 S3 存储桶或创建 link给它。第 8/9 行没有按照我的预期执行,因为它仍然将空文件上传到存储桶并在我的票证上为其创建一个 link。

uploads = [['frontview', 'upload', '<b>Frontview: </b>'],['backview', 'upload2', '<b>Backview: </b>'], ['electricalsupply', 'upload3', '<b>Electrical Supply: </b>'], ['fullstructure', 'upload4', '<b>Full Structure: </b>'], ['controlroom', 'upload5', '<b>Control Room: </b>'], ['otherdoc', 'upload6', '<b>Other Documentation: </b>'], ['customersignoff', 'upload7', '<b>Customer Sign-Off: </b>']]
        file_upload_urls = []
        folder = str(datetime.datetime.now()).replace(' ', '') + '/' # sets folder to the current date & time while getting rid of spaces & adding forward slash for linking purposes
        for upload in uploads: #loops through uploads array
            files = request.files.getlist(upload[1])
            section_urls = []
            for file in files: #loops through uploads array more specifically each File (upload, upload2, upload3, etc)
                if file not in request.files:
                    filename = str(upload[0] + '_' + file.filename).replace(' ', '')
                    section_urls.append(current_app.config['NEVCODOCS_BASE_URL'] + folder + filename)
                    path = "ServiceRegistration/" + folder + filename
                    s3.Bucket('nevcodocs').put_object(Key=path, Body=file)
            file_upload_urls.append([upload[2], section_urls])
​
        # Installation photos are placed in an unordered list & formats links of photos for ticket submission
        for section in file_upload_urls:
            ticket_html = ticket_html + section[0] + '<ul>'
            for url in section[1]:
                ticket_html = ticket_html + '<li> <href=' + url + '">' + url + '</href></li>'
            ticket_html = ticket_html + '</ul>'

下面的代码是上面的一个片段,但我想我会为上下文添加整个函数。我的预期功能是:在遍历每个 FileField 时,检索每个 FileField 的数据,然后 运行 检查是否在每个字段中上传了文件。如果有数据,则将该文件上传到 S3 Bucket。如果 FileField 为空,则循环移动到下一个 FileField。我试过 if len(request.files[file]) != 0if not request.files.get(file, None)if not request.files[file].filename == '' 都无济于事,因为它们要么导致 400 错误请求,要么忽略每个 FileField,即使文件已上传,要么继续上传空白文件。

        for file in files: #loops through uploads array more specifically each FileField (upload, upload2, upload3, etc)
            # if not len(request.files[file]) == 0:
            if file not in files:
                filename = str(upload[0] + '_' + file.filename).replace(' ', '')
                section_urls.append(current_app.config['NEVCODOCS_BASE_URL'] + folder + filename)
                path = "ServiceRegistration/" + folder + filename
                s3.Bucket('nevcodocs').put_object(Key=path, Body=file)

解决方法:if not file.filename == '':