oss_util.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import oss2, logging
  2. import datetime
  3. from config import access_id as ACCESS_KEY_ID, access_key as ACCESS_KEY_SECRET, OSS_ENDPOINT, OSS_BUCKET
  4. logger = logging.getLogger(__name__)
  5. auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
  6. # 填写Bucket名称,CNAME是指将自定义域名绑定到存储空间。
  7. bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET, is_cname=False)
  8. def upload_bytes_to_oss(bytes, oss_file_name):
  9. index = oss_file_name.rfind("/")
  10. file_name = oss_file_name[index+1:]
  11. content_disposition = 'attachment;filename="%s"' % file_name
  12. bucket.put_object(oss_file_name, bytes, headers={'Content-Disposition': content_disposition})
  13. def upload_to_oss(local_file_path, oss_file_name):
  14. """
  15. 上传本地文件到 OSS 文件, 并返回 一定周期内有效的 URL
  16. """
  17. # 上传文件到 OSS
  18. index = oss_file_name.rfind("/")
  19. file_name = oss_file_name[index+1:]
  20. content_disposition = 'attachment;filename="%s"' % file_name
  21. with open(local_file_path, 'rb') as f:
  22. bucket.put_object(oss_file_name, f, headers={'Content-Disposition': content_disposition})
  23. def sign_url(oss_file_name):
  24. # 生成带有有效期的 OSS URL, 生成一个60分钟后过期的下载链接:
  25. expiration_seconds = 60 * 60
  26. url = bucket.sign_url('GET', oss_file_name, expiration_seconds)
  27. url = url.replace("http:", "https:")
  28. logger.info(f'Getting url for {oss_file_name}')
  29. return url
  30. # entry point
  31. if __name__ == '__main__':
  32. local_file_path, oss_file_name = "/data/Downloads/pt-freqDomain.ppt", "Downloads/pt-freqDomain.ppt"
  33. upload_to_oss(local_file_path, oss_file_name)