0

I am in the process of creating a RESTful API using the Python libraries flask-restful and flask. I have managed to get this working perfectly in the case of the functions that return only one image. Such as in the function example below

class GreyShift(Resource):
    def get(self, path):
        final_path = "Images/" + path
        img_location = "temp/greyshift.jpg"
        cv2.imwrite(img_location, cv2.imread(final_path, 0))
        return send_file(img_location, mimetype='image/jpeg')

However, my issue is in the functions where i have to return multiple files in one return. Is there a function to do this in flask? Or is there a better way to accomplish this task.


Update:

Eventually ended up using zipfile library to zip the files together and return them in a single file in the response. As others have pointed out using flask at all to return files is sub-optimal due to it being single threaded. A much better implementation would be to upload the file to a file share service and return a URL link to the file. I did not however, implement this as this was just for a proof of concept application.

Sean Powell
  • 564
  • 4
  • 20

1 Answers1

1

The short answer is that you can look into zipping the files together for transfer.

But the long answer is that, while it's possible to send files using Flask, it's usually not the right tool for the job. The main problem is that Flask is single-threaded, and will thus not be available to handle other requests while it's transferring the files to one user. While you can increase the number of simultaneous connections by using gunicorn or another production server, your goal should in general be to use Flask only to build and serve pages.

Instead, you should put the files you want to transfer on some kind of cloud storage and then send your user links to them. S3 is popular.

Nick K9
  • 3,885
  • 1
  • 29
  • 62
  • Flask is only single-threaded if it's running using its internal development server. For production you should run it under something like uWSGI which will multi-thread it. – TheDavidFactor Jun 16 '19 at 16:23
  • This is true. A lot depends on the scale OP's site needs to run at, and the price he's willing to pay to ensure sufficient server threads for that scale. Heroku, for example, doesn't even let you have more than 1 dyno at the hobby tier. – Nick K9 Jun 16 '19 at 16:46