如果有自己的服务器,可以设置一个定时任务进行脚本运行,就可以实现实时更新文件目录了
[Python] 纯文本查看 复制代码import os
from datetime import datetime
import boto3
endpoint_url = 'https://cn-nb1.rains3.com'
access_key = 'xxxxx'
secret_key = 'xxxxx'
s3 = boto3.client('s3',
endpoint_url=endpoint_url,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
# === 配置 ===
local_dir = "./" # 本地目录路径
bucket_name = "testbox" # 存储桶名称
exclude_files = {"index.html"} # 不列出的文件
# === 生成 index.html ===
def generate_index_html():
# 获取存储桶中的所有文件
try:
response = s3.list_objects_v2(Bucket=bucket_name)
files = []
if 'Contents' in response:
files = [obj['Key'] for obj in response['Contents'] if obj['Key'] not in exclude_files]
# 生成 index.html
html_path = os.path.join(local_dir, "index.html")
with open(html_path, "w", encoding="utf-8") as f:
f.write("\n文件列表"
""
"\n"
"body { font-family: 'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif; margin: 0; padding: 0; background: #f8f9fa; }\n"
".container { max-width: 600px; margin: 0 auto; padding: 16px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.05); border-radius: 8px; margin-top: 24px; }\n"
"h2 { font-size: 1.2rem; margin-bottom: 1em; color: #333; }\n"
"ul { list-style: none; padding: 0; margin: 0; }\n"
"li { border-bottom: 1px solid #eee; }\n"
"li:last-child { border-bottom: none; }\n"
"a { display: block; padding: 12px 8px; color: #007bff; text-decoration: none; word-break: break-all; }\n"
"a:hover { background: #f1f3f5; }\n"
"@media (max-width: 600px) {\n"
" .container { padding: 8px; margin-top: 8px; }\n"
" h2 { font-size: 1rem; }\n"
" a { padding: 10px 4px; font-size: 0.98rem; }\n"
"}\n"
"\n")
f.write(f"存储桶 {bucket_name} 中的文件列表(更新于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')})\n")
for file in sorted(files):
f.write(f"
f.write("
print(f"✅ index.html 生成成功: {html_path}")
# 上传 index.html 到存储桶,显式指定 Content-Type
with open(html_path, 'rb') as f:
s3.upload_fileobj(
f,
bucket_name,
"index.html",
ExtraArgs={'ContentType': 'text/html; charset=utf-8'}
)
print("✅ index.html 已上传到存储桶")
except Exception as e:
print(f"❌ 操作失败: {str(e)}")
# === 执行 ===
if __name__ == "__main__":
generate_index_html()
实现的最终效果页面如下:
[url=]image.png[/url]