How do I upload multiple files using the Flask test_client? How do I upload multiple files using the Flask test_client? flask flask

How do I upload multiple files using the Flask test_client?


The test client takes a list of file objects (as returned by open()), so this is the testing utility I use:

def multi_file_upload(test_client, src_file_paths, dest_folder):    files = []    try:        files = [open(fpath, 'rb') for fpath in src_file_paths]        return test_client.post('/api/upload/', data={            'files': files,            'dest': dest_folder        })    finally:        for fp in files:            fp.close()

I think if you lose your tuples (but keeping the open()s) then your code might work.


Another way of doing this- if you want to explicitly name your file uploads here (my use case was for two CSVs, but could be anything) with test_client is like this:

   resp = test_client.post(                           '/data_upload_api', # flask route                           file_upload_one=[open(FILE_PATH, 'rb')],                           file_upload_two=[open(FILE_PATH_2, 'rb')]                           )

Using this syntax, these files would be accessible as:

request.files['file_upload_one'] # etc.


You should just send data object with your files named as you want:

test_client.post('/api/upload',                  data={'title': 'upload sample',                        'file1': (io.BytesIO(b'get something'), 'file1'),                        'file2': (io.BytesIO(b'forthright'), 'file2')},                   content_type='multipart/form-data')