Aliyun OSS (Object Storage Service) SDK
The `oss2` library is the official Alibaba Cloud OSS (Object Storage Service) SDK for Python. It provides functionalities to interact with OSS, including bucket and object operations like upload, download, and management. The current version is 2.19.1. It is actively maintained with regular updates.
Warnings
- breaking The `oss2` library is a complete rewrite of the previous Alibaba Cloud OSS Python SDK (version 0.x). It is not backward compatible. The package name was specifically changed to `oss2` to avoid conflicts with older installations.
- gotcha When using `oss2.resumable_download` or `oss2.resumable_upload`, avoid calling these functions concurrently from multiple programs or threads targeting the same object and local file. This can lead to checkpoint file corruption, overwrites, or temporary file naming conflicts.
- gotcha For new OSS users accessing buckets in Chinese mainland regions, a custom domain name (CNAME) is required for data API operations starting March 20, 2025. Default public endpoints are restricted for these operations.
- deprecated Python 2.6 and Python 3.3.0/3.3.1 are not recommended due to lack of core team support for 2.6 and a known Python issue (Issue 16658) for 3.3.0/3.3.1.
Install
-
pip install oss2
Imports
- oss2
import oss2
- Auth
from oss2 import Auth
- Bucket
from oss2 import Bucket
- ObjectIterator
from oss2 import ObjectIterator
- exceptions
from oss2 import exceptions
Quickstart
import os
import oss2
# Environment variables for credentials
ACCESS_KEY_ID = os.environ.get('OSS_ACCESS_KEY_ID', 'your-access-key-id')
ACCESS_KEY_SECRET = os.environ.get('OSS_ACCESS_KEY_SECRET', 'your-access-key-secret')
ENDPOINT = os.environ.get('OSS_ENDPOINT', 'http://oss-cn-hangzhou.aliyuncs.com') # e.g., 'http://oss-cn-hangzhou.aliyuncs.com'
BUCKET_NAME = os.environ.get('OSS_BUCKET_NAME', 'your-bucket-name')
# Ensure credentials and endpoint are set
if not all([ACCESS_KEY_ID, ACCESS_KEY_SECRET, ENDPOINT, BUCKET_NAME]):
print("Please set OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_ENDPOINT, and OSS_BUCKET_NAME environment variables.")
exit(1)
try:
# Initialize Auth and Bucket
auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, ENDPOINT, BUCKET_NAME)
# Object key
key = 'hello_oss.txt'
content = 'Hello Alibaba Cloud OSS!'
# 1. Upload an object from memory
bucket.put_object(key, content)
print(f"Object '{key}' uploaded successfully.")
# 2. Download the object content
response = bucket.get_object(key)
downloaded_content = response.read().decode('utf-8')
print(f"Content of '{key}': {downloaded_content}")
# 3. List objects in the bucket (optional)
print("\nObjects in bucket:")
for obj_info in oss2.ObjectIterator(bucket):
print(f" - {obj_info.key}")
# 4. Delete the object
bucket.delete_object(key)
print(f"Object '{key}' deleted successfully.")
except oss2.exceptions.OssError as e:
print(f"OSS Error: {e.code} - {e.message} (Request ID: {e.request_id})")
except Exception as e:
print(f"An unexpected error occurred: {e}")