DEV Community

Gias Uddin
Gias Uddin

Posted on • Updated on

How to upload an object to digital ocean spaces using python boto3 library.

DigitalOcean Spaces is an object storage service provided by DigitalOcean that makes it easy to store, manage, and serve large amounts of data in the cloud. You can use DigitalOcean Spaces to store files and media that you want to serve to users of your Django application. In this article, we will show you how to upload files to DigitalOcean Spaces using Django.

First, you will need to create a DigitalOcean Space and obtain your access keys. You can find instructions on how to do this in the DigitalOcean Spaces documentation.

Get $200 Free credit from Digital ocean From this link, Go Now

Install Boto

pip install boto3
Enter fullscreen mode Exit fullscreen mode

Now create file name upload_space.py

import boto3
import botocore

session = boto3.session.Session()
client = session.client('s3',
                        endpoint_url='https://sfo3.digitaloceanspaces.com',
                        # Find your endpoint in the control panel, under Settings. Prepend "https://".
                        config=botocore.config.Config(s3={'addressing_style': 'virtual'}),
                        region_name='sfo3',  # Use the region in your endpoint.
                        aws_access_key_id='acess_key_id',
                        # Access key pair. You can create access key pairs using the control panel or API.
                        aws_secret_access_key='secreet_key')  # Secret access key defined through an environment variable.

# upload file
with open('path/banner_promo.png', 'rb') as file_contents:
    client.put_object(
        Bucket='myBuket',
        Key='banner_promo.png',
        Body=file_contents,
        ACL='public-read',
        ContentType='image/png'
    )


Enter fullscreen mode Exit fullscreen mode

Now you can upload your file by running this script, by passing your file and content type
Get $200 Free credit from Digital ocean From this link, Go Now

Thank you for reading my article! If you enjoyed it and would like to support my work, please consider buying me a coffee at Buy Me a Coffee. You can also learn more about me and my work by visiting my Giasuddin Bio and following me on LinkedIn and Twitter. Thank you for your support!

Top comments (0)