Search code examples
pythonwerkzeug

python flask: mimic werkzeug FileStorage object


I have the following route in a flask application which accepts an uploaded file and throws the file object into a function for validation. Here's a barebones example:

def is_file_valid(file):
    if file.filename == 'test':
        return True
    return False

@app.route('/validate', method=['POST'])
def validate():
    file = request.files['file']
    if is_file_valid(file):
        return redirect(url_for('somewhere'))
    return redirect(url_for('somewhere_else'))

I'm trying to create a unittest to test the is_file_valid function but I'm having trouble creating the FileStorage object flask uses which appears to be very similar to a standard python file object (docs).

Here's what I've tried so far:

import io
with io.open('/path/to/file', 'rb') as f:
    print(f.filename)

But I'm getting the following error:

AttributeError: 'io.TextIOWrapper' object has no attribute 'filename'

Any idea how I can mimic werkzeug's FileStorage object in a regular python script?


Solution

  • Answered here. Just need to wrap the python file object in the werkzeug FileStorage class.