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.
Common errors
-
ModuleNotFoundError: No module named 'oss2'
cause The `oss2` library is not installed in the Python environment where the code is being executed.fixRun `pip install oss2` in your terminal to install the library. -
SignatureDoesNotMatch
cause The AccessKey ID, AccessKey Secret, or the endpoint used to initialize the `oss2` client is incorrect, or the SDK version is outdated, leading to a mismatch in the signature calculated by the client and the OSS server.fixVerify that your `AccessKeyId`, `AccessKeySecret`, and `endpoint` are correct and match the bucket's region. Ensure your `oss2` library is updated to the latest version. Example: ```python import oss2 import os access_key_id = os.environ.get('OSS_ACCESS_KEY_ID') # Or replace with your actual AccessKeyId access_key_secret = os.environ.get('OSS_ACCESS_KEY_SECRET') # Or replace with your actual AccessKeySecret endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # Replace with your bucket's region-specific endpoint bucket_name = 'your-bucket-name' auth = oss2.Auth(access_key_id, access_key_secret) bucket = oss2.Bucket(auth, endpoint, bucket_name) ``` -
oss2.exceptions.NoSuchKey
cause The specified object key does not exist in the OSS bucket, or the bucket itself does not exist.fixDouble-check the object name (key) and the bucket name to ensure they are correct and exist in your Alibaba Cloud OSS. Example of safe object access: ```python import oss2 # ... (auth and bucket initialization) object_name = 'non_existent_file.txt' try: bucket.get_object(object_name) print(f'Object {object_name} found and retrieved.') except oss2.exceptions.NoSuchKey: print(f'Object {object_name} does not exist.') except oss2.exceptions.ServerError as e: print(f'Server error: {e.status}, Code: {e.code}, Message: {e.message}') ``` -
oss2.exceptions.RequestError
cause This error typically indicates underlying network issues, such as DNS resolution failure, connection timeouts, or other HTTP-level problems during communication with the OSS service.fixVerify your network connectivity, check for correct endpoint URL and region, and ensure no firewalls or proxy settings are blocking access. You may also increase the connection timeout in the `oss2.Bucket` initialization if the network is slow. Example with increased timeout: ```python import oss2 # ... (auth initialization) endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' bucket_name = 'your-bucket-name' bucket = oss2.Bucket(auth, endpoint, bucket_name, connect_timeout=120) # Increase timeout to 120 seconds ``` -
oss2.exceptions.ClientError: HTTP Status: 403, ErrorCode: AccessDenied
cause The provided Alibaba Cloud AccessKeyId, AccessKeySecret, or the associated user's permissions are incorrect or insufficient for the requested OSS operation.fixVerify your `AccessKeyId`, `AccessKeySecret`, `endpoint`, and ensure the associated RAM user/role has the necessary OSS permissions for the specific bucket and object operations.
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.
- breaking The provided Alibaba Cloud OSS Access Key ID is invalid or does not exist in Alibaba Cloud's records. This error prevents any further operations with OSS.
- breaking A generic and empty 'OSS Error' without a specific message or request ID was encountered. This indicates a fundamental issue during interaction with the OSS service where error details could not be retrieved or were suppressed by the SDK. This can be caused by low-level network connectivity problems, incorrect endpoint or bucket configuration, or an unhandled exception within the SDK before specific error details can be reported.
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}")