edit-icon download-icon

Quick start

Last Updated: Oct 20, 2017

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.

View the bucket list

  1. # -*- coding: utf-8 -*-
  2. import oss2
  3. auth = oss2.Auth ('Your AccessKeyID', 'Your AccessKeySecret')
  4. service = oss2.Service(auth, 'Your endpoint')
  5. 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.

Create a bucket

The following code creates a private bucket in the Hangzhou region:

  1. bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'your bucket name')
  2. bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)

Specifically, the oss2.Bucket object is used to upload, download, and delete objects and configure the bucket.

Upload an object

The following code uploads a local file named local.txt to the OSS, and the object name is remote.txt:

  1. bucket.put_object_from_file('remote.txt', 'local.txt')

Download an object

The following code downloads an object from the OSS to a local file:

  1. bucket.get_object_to_file('remote.txt', 'local-backup.txt')

List objects

The following code lists 10 objects in a bucket:

  1. from itertools import islice
  2. for b in islice(oss2.ObjectIterator(bucket), 10):
  3. print(b.key)

The oss2.ObjectIterator object is an iterator, which can be used as other iterators.

Delete an object

  1. bucket.delete_object('remote.txt')
Thank you! We've received your feedback.