tools / utils /oss /oss_upload.py
Adinosaur's picture
Upload folder using huggingface_hub
1c980b1 verified
import argparse
import alibabacloud_oss_v2 as oss
# 创建一个命令行参数解析器,并描述脚本用途:上传文件示例
parser = argparse.ArgumentParser(description="upload file sample")
# 添加命令行参数 --region,表示存储空间所在的区域,必需参数
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令行参数 --bucket,表示要上传文件到的存储空间名称,必需参数
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令行参数 --endpoint,表示其他服务可用来访问OSS的域名,非必需参数
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令行参数 --key,表示对象(文件)在OSS中的键名,必需参数
parser.add_argument('--key', help='The name of the object.', required=True)
# 添加命令行参数 --file_path,表示本地待上传文件的路径,必需参数,例如“/Users/yourLocalPath/yourFileName”
parser.add_argument('--file_path', help='The path of Upload file.', required=True)
def main():
# 解析命令行提供的参数,获取用户输入的值
args = parser.parse_args()
# 从环境变量中加载访问OSS所需的认证信息,用于身份验证
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# 使用SDK的默认配置创建配置对象,并设置认证提供者
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# 设置配置对象的区域属性,根据用户提供的命令行参数
cfg.region = args.region
# 如果提供了自定义endpoint,则更新配置对象中的endpoint属性
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# 使用上述配置初始化OSS客户端,准备与OSS交互
client = oss.Client(cfg)
# 创建一个用于上传文件的对象
uploader = client.uploader()
# 调用方法执行文件上传操作
result = uploader.upload_file(
oss.PutObjectRequest(
bucket=args.bucket, # 指定目标存储空间
key=args.key, # 指定文件在OSS中的名称
),
filepath=args.file_path # 指定本地文件的位置
)
# 打印上传结果的相关信息,包括状态码、请求ID、内容MD5等
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.headers.get("Content-MD5")},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
f' server time: {result.headers.get("x-oss-server-time")},'
)
# 当此脚本被直接执行时,调用main函数开始处理逻辑
if __name__ == "__main__":
main() # 脚本入口点,控制程序流程从这里开始