Aditya Shukla
Aditya Shukla

Reputation: 69

How to upload an image to MongoDB using an S3 bucket and Boto3 in Python

I'm working on a Python application where the desired functionality is that the webcam is used to take in a live video feed and based on whether a condition is true, an image is clicked and uploaded to a database.

The database I am using is MongoDB. As far as I can understand, uploading images straight-up to a database is not the correct method. So, what I wanted to do is the following:

  1. an image is clicked from the webcam
  2. the image is uploaded to an S3 bucket (from the same Python script, so using boto3 perhaps)
  3. a URL of the uploaded image is retrieved (this seems to be the tricky part)
  4. and then this URL along with some other details is uploaded to the database. (this is the easy part)

My ideal workflow would be a way to take that image and upload it to an S3 bucket, retrieve the URL and then upload this URL to the database all in one .py script.

My question is: how do I upload an image to an S3 bucket and then retrieve its public URL all through boto3 in a Python script?

I also welcome any suggestions for a better approach/strategy for storing images into MongoDB. I saw on some pages that GridFS could be a good method but that it is not recommended for the image uploads happening frequently (and really that using AWS is the more preferable way).

Upvotes: 0

Views: 872

Answers (2)

Bert Blommers
Bert Blommers

Reputation: 2093

The URL of an S3 object can be construed if you know the S3 bucket and name:

https://{bucket}.s3.{region}.amazonaws.com/{key}

Using boto3 will be the easiest way to upload a file if you're using Python anyway. See another answer of mine on different ways how to upload files here: https://stackoverflow.com/a/67108609/13245310

Upvotes: 1

E.J. Brennan
E.J. Brennan

Reputation: 46841

You don't need to 'retrieve' the public url, you get to specify the bucket and name of the s3 object when you upload it, so you already have the information you need to know what the public url will be once uploaded, its not like s3 assigns a new unique name to your object once uploaded.

Upvotes: 1

Related Questions