How to download a file from S3/Elastic Beanstalk instance to local machine using Python?


I'm trying to transfer a file from S3 to my local machine. I thought running

s3.download_file('bucket', 'key', 'filename')    
send_file('filename', as_attachment=True)

in my Elastic Beanstalk code will download the file to my local machine but it seems instead to save it on the EB instance instead. No error is being logged either so it's able to download the file, just not to my local machine.

Is there a way to transfer the file from the EB instance to the local computer after EB downloads the file from S3? If there's Boto3 Python code that can do that, that would be really good.

asked 3 months ago48 views
1 Answer
Accepted Answer

Based on the send_file() function, am I right that you're using Flask? If the files are small, it might be easier to just keep the file in memory (using get_object()) rather than downloading it to the server's filesystem. For example, something like:

s3_result = s3.get_object(Bucket='bucket', Key='key')
response = make_response(s3_result['Body'].read())
response.headers['Content-Disposition'] = 'attachment; filename=myfile.txt'
response.mimetype = 'text/plain' # or whatever the MIME type is of your file
return response

If the files are large, you could instead redirect the user to a presigned url (which you can generate using boto3).

answered 3 months ago
profile picture
reviewed 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions