本页面由机器翻译,仅供参考。如有出入,请以英文原文为准。
此目录包含用于将内容上传到支撑 256t.org 的 Cloudflare R2 存储桶的脚本。
存储桶 256t-cids 同时托管:
- CID 文件:内容寻址存储文件(由 r2_upload.py 上传)
- 静态网站文件:生成的网站文件(由 r2_static_upload.py 上传)
两个脚本的所有 R2 操作都使用 Cloudflare 的 Wrangler CLI。
以 CID(内容标识符)作为 R2 中的对象键,实现内容寻址存储。
将 dist/ 目录中的所有静态网站文件上传到 R2,并设置合适的内容类型和缓存响应头。
脚本需要 Wrangler CLI(通过 npm 安装):
npm install -g wrangler
# 或者使用 npx wrangler 一次性执行
python .github/scripts/r2_upload.py examples/hello.txt
python .github/scripts/r2_upload.py examples/hello.txt --verify-only
python .github/scripts/r2_static_upload.py dist
存储桶名称 256t-cids 在两个脚本中都是硬编码的。
脚本使用 Wrangler 向 Cloudflare R2 进行身份验证。你需要:
- CLOUDFLARE_ACCOUNT_ID:你的 Cloudflare 账户 ID
- CLOUDFLARE_API_TOKEN:具有 R2 读写权限的 Cloudflare API 令牌
这些可以设置为环境变量,否则 Wrangler 会提示你进行身份验证。
上传文件时,脚本会:
wrangler r2 object put 256t-cids/{cid} \
--file {filepath} \
--cache-control "public, max-age=31536000, immutable" \
--content-type "application/octet-stream"
脚本通过以下步骤验证对象:
bash
wrangler r2 object get 256t-cids/{cid} --file /tmp/downloaded如果两者一致,则对象有效;否则说明完整性受到破坏。
所有上传的对象都使用以下缓存设置:
Cache-Control: public, max-age=31536000, immutable
这会指示客户端无限期缓存内容,因为按 CID 寻址的内容是不可变的。
要在 GitHub Actions 中使用此脚本,需要在仓库中配置以下密钥:
r2-upload.yml 工作流使用这些密钥向 Cloudflare 进行身份验证:
- name: Upload to R2
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
npm install -g wrangler
python .github/scripts/r2_upload.py examples/hello.txt
验证 CID 对象时:
脚本会处理以下几种错误情况:
这表示存在严重的完整性问题:某个对象以 CID 为键存在,但其内容与预期的 CID 不符。正常运行时绝不应该出现这种情况。
请确保你的 Cloudflare 凭据配置正确:
- 检查 CLOUDFLARE_ACCOUNT_ID 环境变量
- 检查 CLOUDFLARE_API_TOKEN 环境变量
- 确认 API 令牌具有 R2 读写权限
- 确认令牌没有过期
在本地测试脚本:
npm install -g wranglerwrangler loginexport CLOUDFLARE_ACCOUNT_ID=your-account-idpython .github/scripts/r2_upload.py examples/hello.txt注意:Wrangler 也支持使用 --local 标志进行本地 R2 开发,但此脚本是为远程 R2 存储桶设计的。