Report this

What is the reason for this report?

AWS S3 SDK `client.put_object` does not overwrite the existing data in the bucket

Posted on June 17, 2020

I am using the below upload function to upload in a bucket but this does not overwrite the existing file in the bucket. If I upload an image with a particular format and update the image. The overwrite function does not work.

def upload(byte_stream, path, filename):
    bucket = doconn.get_bucket()
    object_key = os.path.join(path, filename)
    params = dict(
        Key=object_key,
        Body=byte_stream,
        ACL='public-read'
    )
    bucket.put_object(**params)
    return object_key


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya,

Just came across this answer and decided to write some general guidelines for anyone who comes across this in the future despite the old question.

With DigitalOcean Spaces, if you want to overwrite an existing file, you simply write a new file with the same object key (file path and file name). From the code snippet you provided, it seems that you’re doing this correctly.

There might be some other issue causing this behavior. One possibility is HTTP caching. Most S3 compatible services, including DigitalOcean Spaces, will add generous Cache-Control headers to response objects by default. You might be seeing the old version of the file due to caching, either in your browser or somewhere else along the way.

If you want to avoid this, you can add a Cache-Control ‘no-cache, no-store, must-revalidate’ parameters to your params dictionary.

  1. params = dict(
  2. Key=object_key,
  3. Body=byte_stream,
  4. ACL='public-read',
  5. CacheControl='no-cache, no-store, must-revalidate'
  6. )

Remember, DigitalOcean Spaces is designed to behave similarly to AWS S3, and should overwrite the file with the newer version when you put an object with an existing key.

For more detailed information, you can refer to DigitalOcean Spaces Documentation.

Hope that this helps!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.