Upgrade OSS SDK for Python from 1.0 to 2.0
OSS SDK for Python 2.0 (alibabacloud_oss_v2) is a full rewrite of v1 (oss2). It replaces scattered function parameters with a unified request/response model, moves all configuration into a single config object, and adds built-in retry, type annotations, and transfer managers. This guide walks you through each change and shows the equivalent v1 and v2 code side by side.
Breaking changes overview
| Area | v1 (oss2) | v2 (alibabacloud_oss_v2) |
|---|---|---|
| Package name | oss2 | alibabacloud_oss_v2 |
| Client creation | oss2.Bucket() | alibabacloud_oss_v2.Client() |
| API calling pattern | Function parameter passing | Request/response model (<OperationName>Request / <OperationName>Result) |
| Signature algorithm | V1 (default) | V4 (default); region required |
| Configuration | Scattered across function parameters | Unified under config object |
| Endpoint | Must specify explicitly | Auto-generated from region for public domains |
| Presigned URL | bucket.sign_url | client.presign |
| Resumable transfers | oss2.resumable_upload / oss2.resumable_download | Uploader / Downloader / Copier |
| Retry | Custom retry logic | Automatic HTTP retries |
| Type annotations | Not available | Complete type annotations |
| Python version | Python 2.7 or later | Python 3.8 or later |
Prerequisites
Before you begin, make sure you have:
Python 3.8 or later. Run
python --versionto check. Download from python.org if needed.OSS SDK for Python 1.0 still installed — keep it running during migration to reduce risk.
A test environment separate from production.
Step 1: Install v2
Install v2 alongside v1. Both can coexist during migration.
pip install alibabacloud-oss-v2Step 2: Update imports
v2 uses a new package name (alibabacloud_oss_v2) and organizes code by functional module. Replace all oss2 imports:
v1:
import oss2v2:
import alibabacloud_oss_v2 as ossImport request and result models explicitly:
from oss.models import (
PutObjectRequest,
GetObjectRequest,
DeleteObjectRequest,
ListObjectsRequest,
PutBucketRequest,
GetBucketAclRequest,
DeleteBucketRequest,
ListBucketsRequest,
CopyObjectRequest,
PresignRequest,
# Add other models as needed
)Import transfer managers and paginators as needed:
from oss import (
Uploader, Downloader, Copier,
ListObjectsPaginator, ListObjectsV2Paginator,
)v2 module structure
| Module | Purpose |
|---|---|
alibabacloud_oss_v2 | Core module — basic and advanced API operations |
alibabacloud_oss_v2.credentials | Credential management and authentication |
alibabacloud_oss_v2.retry | Retry policies |
alibabacloud_oss_v2.signer | Request signing |
alibabacloud_oss_v2.transport | HTTP client configuration |
alibabacloud_oss_v2.crypto | Client-side encryption |
Step 3: Update client creation
In v1, you create a Bucket object that bundles auth, endpoint, and bucket name together. In v2, Client is created from a unified config object, and bucket name is passed per request. v2 uses V4 signature by default and requires a region. For public domain names, it auto-generates the endpoint from the region.
v1:
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)v2:
import alibabacloud_oss_v2 as oss
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = 'cn-hangzhou' # Region is required; endpoint is auto-generated
client = oss.Client(cfg)For all client configuration options, see Configure the client. For credential setup, see Configure access credentials.
Step 4: Update basic API calls
In v2, every basic API operation follows a standard naming pattern: client.<operation_name>(request). Request parameters are wrapped in <OperationName>Request and results are returned as <OperationName>Result. The bucket name moves from client creation to each request object.
Create a bucket
v1:
bucket.create_bucket()
# With ACL:
bucket.create_bucket(oss2.BUCKET_ACL_PRIVATE)v2:
request = PutBucketRequest(bucket='examplebucket')
client.put_bucket(request)
# With ACL:
request = PutBucketRequest(
bucket='examplebucket',
acl=BucketAcl.PRIVATE,
)
client.put_bucket(request)Get bucket ACL
v1:
result = bucket.get_bucket_acl()
acl = result.aclv2:
request = GetBucketAclRequest(bucket='examplebucket')
result = client.get_bucket_acl(request)
acl = result.aclDelete a bucket
v1:
bucket.delete_bucket()v2:
request = DeleteBucketRequest(bucket='examplebucket')
client.delete_bucket(request)List buckets
In v1, listing buckets requires a separate Service object. In v2, Client handles this directly — the Service object no longer exists.
v1:
service = oss2.Service(auth, endpoint)
result = service.list_buckets()
for bucket_info in result.buckets:
print(bucket_info.name)v2:
result = client.list_buckets(ListBucketsRequest())
for bucket_info in result.buckets:
print(bucket_info.name)Upload an object
v1:
# Upload from string/bytes
result = bucket.put_object('object-key', 'content')
# Upload from file
result = bucket.put_object_from_file('object-key', 'local-file.txt')v2:
# Upload from string/bytes
request = PutObjectRequest(
bucket='examplebucket',
key='object-key',
content='content',
)
result = client.put_object(request)
# Upload from file
request = PutObjectRequest(bucket='examplebucket', key='object-key')
result = client.put_object_from_file(request, 'local-file.txt')Download an object
v1:
# Download to memory
result = bucket.get_object('object-key')
content = result.read()
# Download to file
bucket.get_object_to_file('object-key', 'local-file.txt')v2:
# Download to memory
request = GetObjectRequest(bucket='examplebucket', key='object-key')
result = client.get_object(request)
content = result.read()
# Download to file
request = GetObjectRequest(bucket='examplebucket', key='object-key')
client.get_object_to_file(request, 'local-file.txt')Delete an object
v1:
bucket.delete_object('object-key')v2:
request = DeleteObjectRequest(bucket='examplebucket', key='object-key')
client.delete_object(request)List objects
v1 uses an ObjectIterator helper. v2 uses a paginator — list_objects_v2_paginator() returns pages of results and handles pagination automatically.
v1:
for obj in oss2.ObjectIterator(bucket, prefix='photos/'):
print(obj.key)v2:
paginator = client.list_objects_v2_paginator()
for page in paginator.iter_page(oss.ListObjectsV2Request(bucket='examplebucket')):
for obj in page.contents:
print(f'Object: {obj.key}, Size: {obj.size}, Last modified: {obj.last_modified}')For more basic API examples, see Objects and files.
Step 5: Update advanced operations (optional)
Presigned URLs
The presign operation has moved from the Bucket object to the Client object. In v2, client.presign accepts the same request types used for regular API calls. The result also includes the HTTP method, expiration time, and signed headers — not just the URL.
v1 — upload presigned URL:
url = bucket.sign_url('PUT', 'object-key', 3600)v2 — upload presigned URL:
pre_result = client.presign(
oss.PutObjectRequest(bucket='examplebucket', key='object-key'),
expires=timedelta(seconds=3600),
)
# pre_result.url — the presigned URL
# pre_result.method — HTTP method
# pre_result.expiration — expiration datetime
# pre_result.signed_headers — signed request headersv1 — download presigned URL:
url = bucket.sign_url('GET', 'object-key', 3600)v2 — download presigned URL:
pre_result = client.presign(
oss.GetObjectRequest(bucket='examplebucket', key='object-key'),
expires=timedelta(seconds=3600),
)For complete examples, see Upload using a presigned URL and Download using a presigned URL.
Transfer managers
v2 replaces oss2.resumable_upload and oss2.resumable_download with dedicated transfer managers — Uploader, Downloader, and Copier. Create each manager from the client object. All support configurable part sizes, concurrency, and checkpointing.
| Operation | v1 | v2 |
|---|---|---|
| Upload objects | bucket.put_object_from_file | Uploader.upload_file |
| Upload a stream | Not supported | Uploader.upload_from |
| Download to local file | bucket.get_object_to_file | Downloader.download_file |
| Copy objects | bucket.copy_object | Copier.copy |
Uploader
v1:
oss2.resumable_upload(
bucket, 'object-key', 'local-file.zip',
multipart_threshold=100 * 1024,
part_size=100 * 1024,
num_threads=4,
)v2:
uploader = client.uploader()
result = uploader.upload_file(
oss.PutObjectRequest(bucket='examplebucket', key='object-key'),
filepath='local-file.zip',
part_size=10 * 1024 * 1024,
part_num=3,
)Downloader
v1:
oss2.resumable_download(
bucket, 'object-key', 'local-file.zip',
multiget_threshold=100 * 1024,
part_size=100 * 1024,
num_threads=4,
)v2:
downloader = client.downloader()
result = downloader.download_file(
oss.GetObjectRequest(bucket='examplebucket', key='object-key'),
filepath='local-file.zip',
)Copier
v1:
bucket.copy_object('src-bucket', 'src-object', 'dst-object')v2:
copier = client.copier()
result = copier.copy(
oss.CopyObjectRequest(
bucket='examplebucket',
key='dst-object',
source_bucket='src-bucket',
source_key='src-object',
)
)For complete transfer manager examples, see Uploader, Downloader, and Copier.
Step 6: Test and verify
Test incrementally — start with one module before upgrading the rest. This limits the impact if something breaks.
Unit tests: Write test cases for each upgraded feature. Cover:
Basic operations: create, read, update, delete
Boundary conditions: very large or very small payloads, empty inputs
Error handling: network timeouts, invalid inputs, permission errors
Incremental migration: Upgrade one module at a time. After each module passes tests, move to the next. This makes rollbacks targeted rather than wholesale.
Compatibility tests: Verify v2 works across:
Internal systems and architectures
Third-party services your application depends on
Different operating systems and runtime environments
Performance tests: After upgrading, compare v1 and v2 under the same load. Record response times and throughput as a baseline. If performance regresses, tune parameters and optimize code logic.