Aliyun OSS (Object Storage Service) SDK

2.19.1 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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}")

view raw JSON →