Python 阿里云OSS文件上传下载与文件删除及检索示例

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: Python 阿里云OSS文件上传下载与文件删除及检索示例

阿里云OSS文件上传下载与文件删除及检索示例

实践环境

运行环境:

Python 3.5.4

CentOS Linux release 7.4.1708 (Core)/Win10

需要安装以下类库:

pip3 install setuptools_rust1.1.2
pip3 install Crypto
1.4.1 # Win10下,安装后,需要更改 site-packages下crypto包名称为Crypto

pip3 install cryptography3.3.2 # 注意,如果不指定版本,安装oss2时会报错:error: can't find Rust compiler
pip3 install oss2
2.15.0

上传本地文件到阿里云OSS示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import traceback
import os
# 批量上传文件到OSS
def upload_files(bucket, target_dir_path, exclusion_list=[]):
    oss_objects_path = []
    target_dir_path = os.path.normpath(target_dir_path).replace('\\', '/')
    for root, dirs, files in os.walk(target_dir_path):
        for file in files:
            target_file_path = os.path.normpath(os.path.join(root, file))
            target_file_relative_path = target_file_path.replace('\\', '/').replace(target_dir_path, '').lstrip('/')
            if target_file_relative_path in exclusion_list:
                continue
            object_path = 'f2b/artifacts/web-admin-react/%s' % target_file_relative_path
            upload_file(bucket, target_file_path, object_path)
            oss_objects_path.append(object_path)
    return oss_objects_path
# 上传文件到OSS
def upload_file(bucket, target_file_path, object_path):
    with open(target_file_path, 'rb') as fileobj:
        res = bucket.put_object(object_path, fileobj) # object_path为Object的完整路径,路径中不能包含Bucket名称。
        if res.status != 200:
            raise Exception('upload %s error,status:%s' % (target_file_path, res.status))
if __name__ == '__main__':
    try:
        import oss2
        auth = oss2.Auth('ossAccessKeyId', 'ossAccessKeySecret')
        # oss2.Bucket(auth, endpoint, bucket_name)
        # endpoint填写Bucket所在地域对应的endpoint,bucket_name为Bucket名称。以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。
        bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'exampleBucket')
        oss_objects_path = []  # 存放上传成功文件对应的OSS对象相对路径
        target_path = 'D:\\artifact-eb34ea94.tar.gz'
        if not os.path.exists(target_path):
            print('success:false,待上传路径(%s)不存在' %  target_path)
            exit(0)
        if os.path.isdir(target_path): # 如果为目录
            oss_objects_path = upload_files(bucket, target_path)
        else:
            object_path = 'f2b/artifacts/web-admin-react/artifact-eb34ea94.tar.gz'
            upload_file(bucket, target_path, object_path)
            oss_objects_path.append(object_path)
        print(','.join(oss_objects_path))
    except Exception:
        print('success:false,%s' % traceback.format_exc())

参考连接:

https://help.aliyun.com/document_detail/88426.htm?spm=a2c4g.11186623.0.0.9e7e7dbbsOWOh6#t22317.html

https://help.aliyun.com/document_detail/31848.html

下载阿里云OSS文件对象到本地文件示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import traceback
if __name__ == '__main__':
    try:
        import oss2
         auth = oss2.Auth('ossAccessKeyId', 'ossAccessKeySecret')
        # oss2.Bucket(auth, endpoint, bucket_name)
        # endpoint填写Bucket所在地域对应的endpoint,bucket_name为Bucket名称。以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。
        bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'exampleBucket')
        target_file_local_path = 'D:\\artifacts-17a86f.tar.gz' # 本地文件路径
        oss_object_path = 'f2b/artifacts/cloud-f2b-web-admin-react/artifact-eb34ea94.tar.gz'
        # bucket.get_object_to_file('object_path', 'object_local_path')
        # object_path 填写Object完整路径,完整路径中不包含Bucket名称,例如testfolder/exampleobject.txt。
        # object_local_path 下载的Object在本地存储的文件路径,形如 D:\\localpath\\examplefile.txt。如果指定路径的文件存在会覆盖,不存在则新建。
        try:
            res = bucket.get_object_to_file(oss_object_path, target_file_local_path)
            if res.status != 200:
                print('success:false,download fail, unknow exception, status:%s' % res.status)
        except Exception:
            print('success:false,%s' % traceback.format_exc())
    except Exception:
        print('success:false,%s' % traceback.format_exc())

参考连接:

https://help.aliyun.com/document_detail/88442.html

列举指定前缀的所有文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import traceback
if __name__ == '__main__':
    try:
        import oss2
        auth = oss2.Auth('ossAccessKeyId', 'ossAccessKeySecret')
        bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'exampleBucket')
        result_file_list = []
        for obj in oss2.ObjectIteratorV2(bucket,  prefix='f2b/www/alpha/f2b/icec-cloud-f2b-mobile'):
            result_file_list.append(obj.key)
            print(obj.key)
        print(','.join(result_file_list))
    except Exception:
        print('success:false,%s' % traceback.format_exc())

参考连接:

https://help.aliyun.com/document_detail/88458.html

批量删除OSS对象

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import traceback
if __name__ == '__main__':
    try:
        import oss2
        auth = oss2.Auth('ossAccessKeyId', 'ossAccessKeySecret')
        bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'exampleBucket')
        oss_object_path_list = ''.join(sys.argv[1:2]).split(',')
        index = 0
        oss_objects_to_delete = oss_object_path_list[index: index+1000] # API限制,每次最多删除1000个文件
        while oss_objects_to_delete:
            result = bucket.batch_delete_objects(oss_object_path_list[index: index+1000])
            # 打印成功删除的文件名。
            print(result.deleted_keys)
            print('批量删除以下OSS对象成功')
            print(''.join(result.deleted_keys))
            index += 1000
            oss_objects_to_delete = oss_object_path_list[index: index+1000]
    except Exception:
        print('success:false,%s' % traceback.format_exc())

参考连接:

https://help.aliyun.com/document_detail/88463.html

相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
12天前
|
机器学习/深度学习 人工智能 算法
机械视觉:原理、应用及Python代码示例
机械视觉:原理、应用及Python代码示例
|
12天前
|
机器学习/深度学习 人工智能 自然语言处理
人工智能:原理、应用与Python代码示例
人工智能:原理、应用与Python代码示例
|
7天前
|
Serverless Python
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例:加载CSV数据,计算5日、10日和20日MA,然后在K线图上绘制。通过`rolling()`计算平均值,`plot()`函数展示图表,`legend()`添加图例。可利用matplotlib参数自定义样式。查阅matplotlib文档以获取更多定制选项。
20 1
|
11天前
|
存储 安全 网络安全
使用 Python 发送邮件的简单示例
使用Python发送邮件的简单示例,涉及`smtplib`库。配置SMTP服务器(如163.com)地址、端口、邮箱及密码。设置发送者、接收者、邮件主题和内容。创建SMTP对象,登录,发送邮件,并关闭连接。实际操作时,推荐使用SSL/TLS协议并妥善保管密码。
15 0
|
11天前
|
设计模式 人工智能 算法
Python ABC:应用场景和示例
Python ABC:应用场景和示例
21 3
|
12天前
|
数据采集 安全 API
阿里云大学考试python中级题目及解析-python高级
阿里云大学考试python中级题目及解析-python高级
|
12天前
|
存储 SQL 缓存
阿里云大学考试python中级题目及解析-python中级
阿里云大学考试python中级题目及解析-python中级
18 0
|
12天前
|
机器学习/深度学习 存储 数据可视化
阿里云大学考试python初级-python初级
阿里云大学考试python初级-python初级
|
12天前
|
存储 开发工具 数据库
云计算:概念、优势与实践——附Python代码示例
云计算:概念、优势与实践——附Python代码示例
|
13天前
|
NoSQL 关系型数据库 MySQL
[AIGC] 分布式锁及其实现方式详解与Python代码示例
[AIGC] 分布式锁及其实现方式详解与Python代码示例