Aliyun OSS (Object Storage Service) SDK
raw JSON → 2.19.1 verified Tue May 12 auth: no python install: verified quickstart: verified
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.
pip install oss2 Common errors
error ModuleNotFoundError: No module named 'oss2' ↓
cause The `oss2` library is not installed in the Python environment where the code is being executed.
fix
Run
pip install oss2 in your terminal to install the library. error 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.
fix
Verify 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:
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) error oss2.exceptions.NoSuchKey ↓
cause The specified object key does not exist in the OSS bucket, or the bucket itself does not exist.
fix
Double-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:
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}') error 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.
fix
Verify 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:
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 error 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.
fix
Verify 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. ↓
fix Migrate your code to use the `oss2` API. If you have an old `oss` installation, ensure you are importing `oss2` and not `oss`.
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. ↓
fix Ensure that only one instance (program or thread) is performing a resumable operation on a specific object-to-local-file pair at any given time.
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. ↓
fix Configure a custom domain name (CNAME) and bind it to your bucket for data API operations. If using HTTPS, ensure a valid SSL certificate is bound to the custom domain.
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. ↓
fix Use supported Python versions, preferably Python 3.5+.
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. ↓
fix Verify that the `AccessKeyId` and `AccessKeySecret` used to initialize the OSS client are correct and belong to an active Alibaba Cloud account. Ensure there are no typos, leading/trailing spaces, or incorrect characters. If the issue persists, generate new credentials in the Alibaba Cloud console or contact support.
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. ↓
fix Thoroughly review network connectivity to Alibaba Cloud OSS endpoints. Verify that the OSS client is initialized with the correct region, endpoint URL, and bucket name. Ensure API credentials are valid and properly configured. Check for any firewall rules, proxy settings, or DNS issues that might prevent successful communication. Enable verbose logging for the OSS SDK if possible to capture more detailed diagnostic information regarding the underlying cause of the empty error.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) sdist - 1.03s 53.3M
3.10 alpine (musl) - - 0.99s 52.2M
3.10 slim (glibc) sdist 5.8s 0.78s 54M
3.10 slim (glibc) - - 0.77s 53M
3.11 alpine (musl) sdist - 1.32s 58.0M
3.11 alpine (musl) - - 1.47s 56.9M
3.11 slim (glibc) sdist 5.3s 1.23s 59M
3.11 slim (glibc) - - 1.16s 58M
3.12 alpine (musl) sdist - 1.17s 47.4M
3.12 alpine (musl) - - 1.21s 46.4M
3.12 slim (glibc) sdist 8.5s 1.22s 48M
3.12 slim (glibc) - - 1.32s 47M
3.13 alpine (musl) sdist - 1.10s 47.2M
3.13 alpine (musl) - - 1.14s 46.0M
3.13 slim (glibc) sdist 7.5s 1.21s 48M
3.13 slim (glibc) - - 1.21s 47M
3.9 alpine (musl) sdist - 1.00s 53.5M
3.9 alpine (musl) - - 1.02s 52.5M
3.9 slim (glibc) sdist 6.6s 1.05s 54M
3.9 slim (glibc) - - 0.91s 53M
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 verified last tested: 2026-04-24
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}")