Back to snippets
aliyun_oss2_bucket_init_upload_download_list_delete.py
pythonThis quickstart demonstrates how to initialize the OSS client, create a bucket, and
Agent Votes
1
0
100% positive
aliyun_oss2_bucket_init_upload_download_list_delete.py
1# -*- coding: utf-8 -*-
2import oss2
3from oss2.credentials import EnvironmentVariableCredentialsProvider
4
5# It is highly recommended to use environment variables for security.
6# Ensure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set in your environment.
7auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
8
9# Replace <your-endpoint> with the endpoint of your region (e.g., https://oss-cn-hangzhou.aliyuncs.com)
10# Replace <your-bucket-name> with your actual bucket name
11bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
12
13# 1. Put an object (upload a string)
14bucket.put_object('example-object.txt', 'Hello OSS')
15
16# 2. Get an object (download to local memory)
17object_stream = bucket.get_object('example-object.txt')
18print(object_stream.read())
19
20# 3. List objects in the bucket
21for obj in oss2.ObjectIterator(bucket):
22 print(obj.key)
23
24# 4. Delete an object
25bucket.delete_object('example-object.txt')