Python操作阿里云oss

Bucket 存储空间
Object 对象或者文件
Endpoint OSS 访问域名 Region 区域或者数据中心
AccessKey AccessKeyId 和 AccessKeySecret 的统称,访问密钥

一 安装阿里云第三方库oss2

pip3 install oss2

api文档地址:https://aliyun-oss-python-sdk.readthedocs.io/en/stable/api.html#id12

二 重要参数说明

工作当中,如果要操作oss,需要向管理员(运维人员)申请bucket,以及bucket对的key来获取操作的权限。

涉及到需要申请的参数如下:

  • ​bucket_name 操作空间名称
  • (access_id, access_key )管理员开通的对应key信息(注意区分个人key和项目key)
  • ​endpoint 对外服务的访问域名,例如:http://oss-cn-hangzhou.aliyuncs.com

三 代码展示

注意:oss不存在路径概念,这里的路径指key,示例代码封装了一些常用的方法,安装完成oss2后可以直接拿来使用,其他不常用方法的请查看api文档。

import oss2
from itertools import islice


class ConnectOss(object):
    def __init__(self, access_id, access_key, bucket_name):
        """验证权限"""
        self.auth = oss2.Auth(access_id, access_key)
        self.endpoint = 'http://oss-cn-hangzhou.aliyuncs.com'
        self.bucket = oss2.Bucket(self.auth, self.endpoint, bucket_name=bucket_name)

    def get_bucket_list(self):
        """列举当前endpoint下所有的bucket_name"""
        service = oss2.Service(self.auth, self.endpoint)
        bucket_list = [b.name for b in oss2.BucketIterator(service)]
        return bucket_list

    def get_all_file(self, prefix):
      """获取指定前缀下所有文件"""
        for b in islice(oss2.ObjectIterator(self.bucket, prefix=prefix), 10):
            yield b.key

    def read_file(self, path):
        try:
            file_info = self.bucket.get_object(path).read()
            return file_info
        except Exception as e:
            print(e, '文件不存在')

    def download_file(self, path, save_path):
        result = self.bucket.get_object_to_file(path, save_path)
        if result.status == 200:
            print('下载完成')

    def upload_file(self, path, local_path):
        result = self.bucket.put_object_from_file(path, local_path)
        if result.status == 200:
            print('上传完成')


if __name__ == '__main__':
  	access_id = '***'
    access_key = '***'
    bucket_name = '***'
    co = ConnectOss(access_id, access_key, bucket_name)

这样可以通过脚本跨平台支持文件的上传下载了


版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_39813400/article/details/120021308