用python调试一下oss对象存储。
一开始用的oss2库,发现不行。用boto3库才可以,说明我的对象存储是和AWS兼容的,并不是基于阿里的oss.
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)
列出桶中的文件
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}')
上传图片到桶里
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}')
下载桶中的图片
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}')
标签:存储,file,python,oss,except,access,key,print,name From: https://www.cnblogs.com/ggborn-001/p/18569354