以下示例演示如何使用 S3 API 和 API 令牌对 R2 进行身份验证。
运行任一示例前,请确保已设置以下环境变量。更多信息请参阅身份验证。
export AWS_REGION=auto
export AWS_ENDPOINT_URL=https://<account_id>.r2.cloudflarestorage.com
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key安装 S3 API 的 @aws-sdk/client-s3 包:
npm i @aws-sdk/client-s3yarn add @aws-sdk/client-s3pnpm add @aws-sdk/client-s3bun add @aws-sdk/client-s3使用 node index.js 运行以下 Node.js 脚本。请确保将 Bucket 更改为存储桶名称,将 Key 指向 R2 存储桶中的现有文件。
注意,以下教程对 TypeScript 同样适用。
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
const s3 = new S3Client();
const Bucket = "<YOUR_BUCKET_NAME>";
const Key = "pfp.jpg";
const object = await s3.send(
new GetObjectCommand({
Bucket,
Key,
}),
);
console.log("Successfully fetched the object", object.$metadata);
// Process the data as needed
// For example, to get the content as a Buffer:
// const content = data.Body;
// Or to save the file (requires 'fs' module):
// import { writeFile } from "node:fs/promises";
// await writeFile('ingested_0001.parquet', data.Body);安装 boto3 S3 API 客户端:
pip install boto3使用 python3 get_r2_object.py 运行以下 Python 脚本。请确保将 bucket 更改为存储桶名称,将 object_key 指向 R2 存储桶中的现有文件。
import boto3
from botocore.client import Config
# Configure the S3 client for Cloudflare R2
s3_client = boto3.client('s3',
config=Config(signature_version='s3v4')
)
# Specify the object key
#
bucket = '<YOUR_BUCKET_NAME>'
object_key = '2024/08/02/ingested_0001.parquet'
try:
# Fetch the object
response = s3_client.get_object(Bucket=bucket, Key=object_key)
print('Successfully fetched the object')
# Process the response content as needed
# For example, to read the content:
# object_content = response['Body'].read()
# Or to save the file:
# with open('ingested_0001.parquet', 'wb') as f:
# f.write(response['Body'].read())
except Exception as e:
print(f'Failed to fetch the object. Error: {str(e)}')使用 go get 将 aws-sdk-go-v2 包添加到 Go 项目:
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/credentials
go get github.com/aws/aws-sdk-go-v2/service/s3使用 go run main.go 将以下 Go 应用程序作为脚本运行。请确保将 bucket 更改为存储桶名称,将 objectKey 指向 R2 存储桶中的现有文件。
package main
import (
"context"
"fmt"
"io"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func main() {
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
log.Fatalf("Unable to load SDK config, %v", err)
}
// Create an S3 client
client := s3.NewFromConfig(cfg)
// Specify the object key
bucket := "<YOUR_BUCKET_NAME>"
objectKey := "pfp.jpg"
// Fetch the object
output, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Unable to fetch object, %v", err)
}
defer output.Body.Close()
fmt.Println("Successfully fetched the object")
// Process the object content as needed
// For example, to save the file:
// file, err := os.Create("ingested_0001.parquet")
// if err != nil {
// log.Fatalf("Unable to create file, %v", err)
// }
// defer file.Close()
// _, err = io.Copy(file, output.Body)
// if err != nil {
// log.Fatalf("Unable to write file, %v", err)
// }
// Or to read the content:
content, err := io.ReadAll(output.Body)
if err != nil {
log.Fatalf("Unable to read object content, %v", err)
}
fmt.Printf("Object content length: %d bytes\n", len(content))
}