python连接操作oss对象存储

用python调试一下oss对象存储。

一开始用的oss2库,发现不行。用boto3库才可以,说明我的对象存储是和AWS兼容的,并不是基于阿里的oss.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError
 
# 设置您的Access Key和Secret Key
access_key_id = 'SIEKD893517E47BCBA5F4F9BF38AB208372'
access_key_secret = 'XXXXXX538s78YYUSJJEISHFYESJDUEHSJ'
endpoint = 'https://example.com'
bucket_name = 'test'
object_key = '00115c8b746f4cd99325efd35881c1e0.png'  # 替换为你想下载的对象名称
file_path = r"C:\Users\31317\Pictures\Saved Pictures\00115c8b746f4cd99325efd35881c1e0.png"
local_file_path =  r"D:\stu\iso\00115c8b746f4cd99325efd35881c1e0.png"
 
# 创建S3客户端
s3 = boto3.client('s3',
                  aws_access_key_id=access_key_id,
                  aws_secret_access_key=access_key_secret,
                  endpoint_url=endpoint)

 列出桶中的文件

1
2
3
4
5
6
7
8
9
10
11
12
try:
    # 列出桶中的对象
    response = s3.list_objects_v2(Bucket=bucket_name)
    for obj in response.get('Contents', []):
        print('Object name:', obj['Key'])
 
except NoCredentialsError:
    print('Credentials not available.')
except PartialCredentialsError:
    print('Incomplete credentials provided.')
except Exception as e:
    print(f'Error occurred: {e}')

 上传图片到桶里

1
2
3
4
5
6
7
8
9
10
11
try:
    # 上传文件到桶
    s3.upload_file(Filename=file_path, Bucket=bucket_name, Key=object_key)
    print(f"成功上传图片 {file_path} 到 {bucket_name} 作为 {object_key}")
 
except NoCredentialsError:
    print('Credentials not available.')
except PartialCredentialsError:
    print('Incomplete credentials provided.')
except Exception as e:
    print(f'Error occurred: {e}')

 下载桶中的图片

1
2
3
4
5
6
7
8
9
10
11
try:
    # 下载对象到本地文件
    s3.download_file(Bucket=bucket_name, Key=object_key, Filename=local_file_path)
    print(f"成功下载文件: {object_key} 到 {local_file_path}")
 
except NoCredentialsError:
    print('Credentials not available.')
except PartialCredentialsError:
    print('Incomplete credentials provided.')
except Exception as e:
    print(f'Error occurred: {e}')

  

posted @   高佳丰  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示