Serve static files in Flask from private AWS S3 bucket Serve static files in Flask from private AWS S3 bucket flask flask

Serve static files in Flask from private AWS S3 bucket


The preferred way is to simply create a pre-signed URL for the image, and return a redirect to that URL. This keeps the files private in S3, but generates a temporary, time limited, URL that can be used to download the file directly from S3. That will greatly reduce the amount of work happening on your server, as well as the amount of data transfer being consumed by your server. Something like this:

@app.route('/download/<resource>')def download_image(resource):    """ resource: name of the file to download"""    s3 = boto3.client('s3',                      aws_access_key_id=current_app.config['S3_ACCESS_KEY'],                      aws_secret_access_key=current_app.config['S3_SECRET_KEY'])    url = s3.generate_presigned_url('get_object', Params = {'Bucket': 'S3_BUCKET_NAME', 'Key': resource}, ExpiresIn = 100)    return redirect(url, code=302)

If you don't like that solution, you should at least look into streaming the file contents from S3 instead of writing it to the file system.