Registry / aws / oss2

oss2

JSON →
library2.19.1pypypi✓ verified 52d ago

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.

awshttp-networkingserialization
pip install oss2
Install & Compatibility
Where this runs
tested against v2.19.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 1.126s · 53.3MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 6.7s · import 1.089s · 54MB
52MB installed
● package 52MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

oss2
import oss2
Primary import for the SDK classes and functions.
Auth
from oss2 import Auth
Used for authentication with AccessKeyID and AccessKeySecret.
Bucket
from oss2 import Bucket
Represents an OSS bucket, used for bucket and object operations.
ObjectIterator
from oss2 import ObjectIterator
Iterator for listing objects within a bucket.
exceptions
from oss2 import exceptions
Contains custom exceptions thrown by the SDK, e.g., `oss2.exceptions.NoSuchKey`.

This quickstart demonstrates how to initialize the `oss2` SDK, upload a string to an object, download its content, list objects in the bucket, and then delete the uploaded object. It uses environment variables for secure credential management.

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}")
Debug
Known issues
breakingThe `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`.
affects: All versions 2.x compared to 0.x
gotchaWhen 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.
affects: All versions 2.x
gotchaFor 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.
affects: New OSS users (registered after March 20, 2025) accessing Chinese mainland regions.
deprecatedPython 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+.
affects: All versions 2.x when used with Python 2.6, 3.3.0, or 3.3.1
breakingThe 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.
affects: All versions 2.x
breakingA 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.
affects: All versions 2.x
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'oss2'
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.
SignatureDoesNotMatch
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:
```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
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:
```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
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:
```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
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.
Upgrade
Version history
2.19.1latest on PyPI
Audit
Dependencies
requestsrequiredUsed for underlying HTTP communication.
crcmodrequiredUsed for CRC (Cyclic Redundancy Check) calculations.
Agent activity
13 hits · last 30 days
seranking-bot
4
node
2
ahrefsbot
2
bytedance
2
Amazon
1
Resources