0

I'm following the file uploads example from the Flask docs.

There is an if file check before saving the file. When does this return false? It's already been checked that the file does exist and has a filename. It returns True when the file is empty.

If the file is None, the file not in request.files returns False, so the code never gets to the if file part. I just want to know why this check is done.

I have a feeling this question is probably silly and obvious, but I wasn't able to find anything on Google.

Snippet:

@app.route('/file/<string:filename>', methods=['POST'])
def upload_file(filename):
    if 'file' not in request.files:
        return "No file part in request", 400
    file = request.files['file']
    if file.filename == '':
        return "No selected file", 400
    if file:
        filename = secure_filename(filename)
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        return "File uploaded successfully"
    else:
        return "Something went wrong but I don't know what", 400
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79

1 Answers1

1

The request.files[] returns a FileStorage object, and from its source code, it's boolean value depends on the boolean value of its filename

def __nonzero__(self):
    return bool(self.filename)

__bool__ = __nonzero__

So the purpose of if file should be when the filename is not empty but falsy, I could though of None but I don't know how it could be this value, for me the filename could just be a string, empty of not, but that's how the tutorial suggest to do now.

azro
  • 53,056
  • 7
  • 34
  • 70