DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Shrawan
Shrawan

Posted on • Originally published at shrawanx.com

Cloudflare R2 - Generating Presigned URL

Since, cloudflare R2 is compatible with S3 API, we can simply use boto3 to work with R2 as wll

import logging
import boto3
from botocore.exceptions import ClientError

from botocore.client import Config


def create_presigned_url(bucket_name, object_name, expiration=3600):
    s3_client = boto3.client('s3',
            endpoint_url='https://<ACCOUNT_ID>.r2.cloudflarestorage.com',
            aws_access_key_id='<ACCESS_KEY>',
            aws_secret_access_key='<SECRET_KEY>',
            config=Config(signature_version='s3v4'),
      )
    try:
        response = s3_client.generate_presigned_url('get_object',
                    Params={'Bucket': bucket_name,
                                    'Key': object_name},
                                     ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

    # The response contains the presigned URL
    return response
Enter fullscreen mode Exit fullscreen mode

if you want to use R2 with Django have a look into https://djangotherightway.com/using-cloudflare-r2-with-django-for-storage

Top comments (0)

DEV runs on 100% open source code known as Forem.

Β 
Contribute to the codebase or host your own.
Β 
Check these out! πŸ‘‡