Alibaba Cloud OSS SDK V2 for Python

1.2.5 · active · verified Tue Apr 14

alibabacloud-oss-v2 is the second major version of the Alibaba Cloud OSS (Object Storage Service) SDK for Python. It is a significant rewrite, aiming to simplify underlying operations like authentication, automatic request retries, and error handling, while offering flexible parameter configuration and advanced features such as paginators and transmission managers. The library is currently at version 1.2.5 and receives frequent updates, indicating active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the OSS V2 client using environment variables for credentials and then list all accessible OSS buckets. Ensure you set `ALIBABA_CLOUD_ACCESS_KEY_ID`, `ALIBABA_CLOUD_ACCESS_KEY_SECRET`, and `ALIBABA_CLOUD_REGION_ID` environment variables for authentication.

import os
from alibabacloud_oss_v2 import client as oss_client
from alibabacloud_oss_v2 import models as oss_models
from alibabacloud_oss_v2 import config as oss_config
from alibabacloud_oss_v2.credentials import EnvironmentVariableCredentialsProvider

# Set environment variables for authentication (replace with your actual region and credentials)
# os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = 'your_access_key_id'
# os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = 'your_access_key_secret'
# os.environ['ALIBABA_CLOUD_REGION_ID'] = 'cn-hangzhou'

region = os.environ.get('ALIBABA_CLOUD_REGION_ID', 'cn-hangzhou')

try:
    # Loading credentials from environment variables
    credentials_provider = EnvironmentVariableCredentialsProvider()

    # Using the SDK's default configuration
    cfg = oss_config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = region

    client = oss_client.Client(cfg)

    # Create a Paginator for the ListBuckets operation
    paginator = client.list_buckets_paginator()

    print(f"Listing buckets in region: {region}")
    # Iterate through the bucket pages
    found_buckets = False
    for page in paginator.iter_page(oss_models.ListBucketsRequest()):
        for bucket_info in page.buckets:
            print(f'Bucket: {bucket_info.name}, Location: {bucket_info.location}, Creation Date: {bucket_info.creation_date}')
            found_buckets = True
    if not found_buckets:
        print("No buckets found or access denied.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set.")

view raw JSON →