It is necessary to understand OSS Basic Concepts, such as bucket, object, endpoint, AccessKeyId, and AccessKeySecret.
This document describes how to use the OSS Python SDK to access OSS, that includes viewing the bucket list, uploading and downloading objects, and viewing the object list.
These programs are written in a script object by default, and can be executed through Python. Besides, the examples provided here, may depend on the previous ones. You can copy these examples to a Python interactive environment for test.
Note:Never use production buckets to test examples in this document.
# -*- coding: utf-8 -*-
auth = oss2.Auth ('Your AccessKeyID', 'Your AccessKeySecret')
service = oss2.Service(auth, 'Your endpoint')
print([b.name for b in oss2.BucketIterator(service)])
Classes in the preceding code:
The oss2.Auth object contains the user’s authentication information, that is, AccessKeyID, and AccessKeySecret.
The oss2.Service object is used for service-related operations. Currently, it is used to list buckets.
The oss2.BucketIterator object is an iterator capable of traversing the user’s bucket information.
The following code creates a private bucket in the Hangzhou region:
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'your bucket name')
Specifically, the oss2.Bucket object is used to upload, download, and delete objects and configure the bucket.
The following code uploads a local file named local.txt to the OSS, and the object name is remote.txt:
The following code downloads an object from the OSS to a local file:
The following code lists 10 objects in a bucket:
from itertools import islice
for b in islice(oss2.ObjectIterator(bucket), 10):
The oss2.ObjectIterator object is an iterator, which can be used as other iterators.