title: 对象存储服务oss初探subtitle: 对象存储服务oss初探
date: 2021-07-14
author: NSX
catalog: true
tags:
- oss

oss 简介

对象存储服务(Object Storage Service,OSS)是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。

简单使用示例

  1. import oss2
  2. class oss(object):
  3. """对象存储类,将模型传至阿里云端"""
  4. def __init__(self, access_key_id, access_key_secret, endpoint, bucket_name):
  5. self.auth = oss2.Auth(access_key_id, access_key_secret)
  6. self.bucket = oss2.Bucket(self.auth, endpoint, bucket_name) # 连接OSS
  7. def put_file(self, file_path, oss_path):
  8. with open("{}".format(file_path), "rb") as f:
  9. put_result = self.bucket.put_object(oss_path, f)
  10. if put_result.status == 200:
  11. # 若此时的status状态为200,则说明上传成功;
  12. print("put success")
  13. def get_file(self, file_path, oss_path):
  14. # param1:oss上bucket中的文件名
  15. # param2:保存在当地的文件路径+文件名
  16. get_result = self.bucket.get_object_to_file(oss_path, file_path)
  17. if get_result.status == 200:
  18. print("get success")
  19. else:
  20. print("get failed")
  21. oss_server = oss(
  22. access_key_id="AccessKey"),
  23. access_key_secret="AccessKeySecret"),
  24. endpoint="EndPoint",
  25. bucket_name="Bucket",
  26. )
  27. def download_longfor_bert(pretrain_file, oss_get_path):
  28. """获取OSS指定目录下的文件
  29. """
  30. for obj in oss2.ObjectIterator(oss_server.bucket, prefix = oss_get_path, delimiter = '/'):
  31. # 通过is_prefix方法判断obj是否为文件夹。
  32. if obj.is_prefix(): # 判断obj为文件夹。
  33. print('directory: ' + obj.key)
  34. else: # 判断obj为文件。
  35. print('file: ' + obj.key)
  36. file_name = str(obj.key).split('/')[-1]
  37. if file_name:
  38. oss_server.get_file(pretrain_file+file_name, obj.key)

参考

https://help.aliyun.com/product/31815.html?spm=a2c4g.11174283.6.540.47ce4c07QFiKcz