记录:使用 Python 操作 Cloudflare R2 对象存储

发布时间 2024-01-01 17:49:02作者: BuckyI

创建存储桶:仪表盘 -- R2 -- 创建存储桶

R2 界面右上角 -- 管理 R2 API 令牌 -- 创建 API 令牌

cloudflare/python-cloudflare: Python wrapper for the Cloudflare Client API v4 python API 封装
尝试了一下后,不会用,也没有文档,放弃

Cloudflare API Documentation Cloudflare 的 API 文档
S3 · Cloudflare R2 docs R2 存储的 API 文档

The API is available via the https://<ACCOUNT_ID>.r2.cloudflarestorage.com endpoint.

注意:这里获得的是 API 密钥,账户详细信息里面,还有个账户 id,后面都会用到。

文档中有各种语言调用 API 的代码示例,比如说查看所有的 buckets

import http.client

account_identifier = "XXX"  # 前面的账户 id
api_key = "XXX"  # 前面获得的 api key

conn = http.client.HTTPSConnection("api.cloudflare.com")

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}",
}

conn.request(
    "GET", f"/client/v4/accounts/{account_identifier}/r2/buckets", headers=headers
)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

不过这里 API 好像只支持 bucket 的查看,创建,删除,不能进行文件的操作。

(暂缓……)