This topic describes how to use Object Storage Service (OSS) SDK for Python to perform common operations, such as creating buckets, uploading objects, and downloading objects.
Usage notes
For more information about supported regions and endpoints, see Regions and endpoints.
In this topic, access credentials obtained from environment variables are used. For more information about how to configure the access credentials, see Configure access credentials using OSS SDK for Python 1.0.
In this topic, OSS SDK for Python is initialized by using default configurations. For information about the sample code for other scenarios, see Initialization.
Prerequisites
An Alibaba Cloud Account is created.
OSS is activated.
Configure environment variables
Configure environment variables for the AccessKey pair.
Linux
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrcApply the changes.
source ~/.bashrcCheck whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to view the default shell type:
echo $SHELLConfigure environment variables based on the default shell type.
Zsh
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrcApply the changes.
source ~/.zshrcCheck whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profileApply the changes.
source ~/.bash_profileCheck whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in PowerShell:
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
After you set the environment variables, you must restart any open terminal sessions or IDEs for the changes to take effect.
Install OSS SDK for Python
Ensure that you have a compatible version of Python installed. Run the following command to check your Python version:
OSS SDK for Python is compatible with Python 2.6, 2.7, and versions 3.3 and later.
python -versionIf you do not have Python installed, download and install it from the official Python website.
Install OSS SDK for Python.
Run the following command to install OSS SDK for Python:
pip install oss2
Sample code
The following sample code demonstrates the complete workflow of using the OSS SDK for Python, including creating a bucket, uploading an object, downloading an object, listing objects, and cleaning up by deleting the objects and the bucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice
import os
import logging
import time
import random
# Configure logs.
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Check whether the environment variables are configured.
required_env_vars = ['OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_SECRET']
for var in required_env_vars:
if var not in os.environ:
logging.error(f"Environment variable {var} is not set.")
exit(1)
# Obtain access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint and region.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
def generate_unique_bucket_name():
# Query the current timestamp.
timestamp = int(time.time())
# Generate a random number from 0 to 9999.
random_number = random.randint(0, 9999)
# Specify the name of the bucket. The name must be globally unique.
bucket_name = f"demo-{timestamp}-{random_number}"
return bucket_name
# Generate a unique bucket name.
bucket_name = generate_unique_bucket_name()
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
def create_bucket(bucket):
try:
bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)
logging.info("Bucket created successfully")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to create bucket: {e}")
def upload_file(bucket, object_name, data):
try:
result = bucket.put_object(object_name, data)
logging.info(f"File uploaded successfully, status code: {result.status}")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to upload file: {e}")
def download_file(bucket, object_name):
try:
file_obj = bucket.get_object(object_name)
content = file_obj.read().decode('utf-8')
logging.info("File content:")
logging.info(content)
return content
except oss2.exceptions.OssError as e:
logging.error(f"Failed to download file: {e}")
def list_objects(bucket):
try:
objects = list(islice(oss2.ObjectIterator(bucket), 10))
for obj in objects:
logging.info(obj.key)
except oss2.exceptions.OssError as e:
logging.error(f"Failed to list objects: {e}")
def delete_objects(bucket):
try:
objects = list(islice(oss2.ObjectIterator(bucket), 100))
if objects:
for obj in objects:
bucket.delete_object(obj.key)
logging.info(f"Deleted object: {obj.key}")
else:
logging.info("No objects to delete")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to delete objects: {e}")
def delete_bucket(bucket):
try:
bucket.delete_bucket()
logging.info("Bucket deleted successfully")
except oss2.exceptions.OssError as e:
logging.error(f"Failed to delete bucket: {e}")
# The following sample code provides an example of the main process of using OSS SDK for Python to perform common operations.
if __name__ == '__main__':
# 1: Create a bucket.
create_bucket(bucket)
# 2. Upload a string as an object.
upload_file(bucket, 'test-string-file', b'Hello OSS, this is a test string.')
# 3. Download an object from the bucket.
download_file(bucket, 'test-string-file')
# 4. List objects in the bucket.
list_objects(bucket)
# 5. Delete all objects in the bucket.
delete_objects(bucket)
# 6. Delete the bucket.
delete_bucket(bucket)

