API document

Basic classes

class oss2.Auth(access_key_id, access_key_secret)[source]

The first version of the signature. Stores AccessKeyId and AccessKeySecret of the user, and calculates the signature.

class oss2.AnonymousAuth[source]

Anonymous Auth

Note

Anonymous users can only read buckets with public-read permissions, or read from or write to buckets with public-read-write permissions. They are unable to execute service or bucket related operations, such as listing objects under a bucket.

class oss2.StsAuth(access_key_id, access_key_secret, security_token, auth_version='v1')[source]

Used for STS authentication. Users can get the AccessKeyID, AccessKeySecret, and SecurityToken from the Alibaba Cloud STS service (https://aliyuncs.com).

Note

The AccessKeyId/Secret and SecurityToken have expiration times. When they are renewed, the STSAuth property of class Bucket instance must be updated with the new credentials.

Parameters:
  • access_key_id (str) – Temporary AccessKeyId
  • access_key_secret (str) – Temporary AccessKeySecret
  • security_token (str) – Temporary SecurityToken
  • auth_version (str) – The version of the auth needs to be generated, the default value is AUTH_VERSION_1(v1).
class oss2.Bucket(auth, endpoint, bucket_name, is_cname=False, session=None, connect_timeout=None, app_name='', enable_crc=True)[source]

The class for Bucket or Object related operations, such as the creation or deletion of buckets, and the upload or download of objects.

Usage (A Bucket in the Hangzhou data center is used as an example):
>>> import oss2
>>> auth = oss2.Auth('your-access-key-id', 'your-access-key-secret')
>>> bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'your-bucket')
>>> bucket.put_object('readme.txt', 'content of the object')
<oss2.models.PutObjectResult object at 0x029B9930>
Parameters:
  • auth (oss2.Auth) – Auth object that contains the AccessKeyId and AccessKeySecret of the user.
  • endpoint (str) – Domain name of endpoint or the CName.
  • bucket_name (str) – Bucket name
  • is_cname (bool) – True if the endpoint is CNAME. Otherwise, it is False.
  • session (oss2.Session) – Session instance. None if creating a new session.
  • connect_timeout (float) – Connection timeout in seconds.
  • app_name (str) – App name. If it is not empty, the name will be appended in User Agent. Note that this value will be a part of the HTTP Header value and thus must follow http protocol’s format.
class oss2.Service(auth, endpoint, session=None, connect_timeout=None, app_name='')[source]

The class for interacting with Service related operations, such as listing all buckets.

Usage:
>>> import oss2
>>> auth = oss2.Auth('your-access-key-id', 'your-access-key-secret')
>>> service = oss2.Service(auth, 'oss-cn-hangzhou.aliyuncs.com')
>>> service.list_buckets()
<oss2.models.ListBucketsResult object at 0x0299FAB0>
Parameters:
  • auth (oss2.Auth) – The auth instance that contains access-key-id and access-key-secret.
  • endpoint (str) – The endpoint domain, such as ‘oss-cn-hangzhou.aliyuncs.com’.
  • session (oss2.Session) – The session instance. If specified as None, a new session is used. Otherwise, it will reuse the previous session.
  • connect_timeout (float) – The connection timeout in seconds.
  • app_name (str) – App name. If this is not empty, it will be appended in the User Agent header. Note that this value will be a part of the HTTP Header value and thus must follow http protocol’s format.
class oss2.Session[source]

Requests of the same session share the same connection pool and possibly the same HTTP connection.

Input, output, and exception description

Data parameters for file upload methods

For example, put_object has the data parameter. It can be any one of the following types:
  • unicode type (for Python3 it is str): Internally converted to UTF-8 bytes.
  • bytes types: No conversion
  • file-like object: For seekable and tellable file object, it will read from the current position to the end. Otherwise, make sure the current position is the file start position.
  • Iterator types: The data must be of the iterator type if its length is not predictable. Chunked Encoding is used internally for transfer operations.

The input paramater in bucket config update methods

For example put_bucket_cors has the input parameter. It can be any of the following types:
  • Bucket config related class such as BucketCors
  • unicode type (For Python3, it is str)
  • UTF-8 encoded bytes
  • file-like object
  • Iterator types, uses Chunked Encoding for transfer

Except supporting the Bucket configuration related class, the input parameter has the same types as the data parameters.

Return value

Most methods in Service and Bucket return RequestResult or its subclasses. RequestResult class defines the HTTP status code, response headers and OSS Request ID. The subclasses of RequestResult define the specific data that is of interest to users. For example, ListBucketsResult.buckets returns the Bucket instance list. and GetObjectResult returns a file-like object which can call read() to get the response body.

Encrypted interface CryptoBucket :

CryptoBucket provides encrypted interfaces only for upload/download data, such as get_object and put_object. The CryptoBucket return values are the same as for the corresponding Bucket interfaces.

Exceptions

In general, Python SDK can throw up three Exception types, which are inherited from OssError .
  • ClientError : Client side exceptions due to the user’s incorrect usage parameters.
  • ServerError and its subclasses : Server side exceptions which contain error codes such as 4xx or 5xx.
  • RequestError : The underlying requests lib’s exceptions, such as DNS error or timeout.

Besides these, Bucket.put_object_from_file and Bucket.get_object_to_file may throw file-related exceptions.

Download range

For example, get_object and upload_part_copy have the byte_range parameter, which specifies the read range. It is a 2-tuple: (start,last). These methods internally would translate the tuple into the value of Http header Range, such as:

  • For (0, 99), the translated Range header is ‘bytes=0-99’, which means reading the first 100 bytes.
  • For (None, 99), the translated Range header is ‘bytes=-99’, which means reading the last 99 bytes
  • For (100, None), the translated Range header is ‘bytes=100-‘, which means reading the whole data starting from the 101th character (The index is 100 and index starts with 0).

Paging

Lists APIs such as list_buckets and list_objects support paging. Specify the paging markers, for example, marker or key_marker, to query a specific page after that marker. For the first page, the marker is empty, which is the default value. For the following pages, use the next_marker or next_key_marker value as the marker value. Check the is_truncated value after each call to determine if it is the last page. If the value is false, it means it is the last page.

Upload or Download Progress

Upload or Download APIs such as get_object, put_object, resumable_upload support the progress callback method. Users can use it to implement progress bars or other functions when the progress of data is important.

progress_callback definition:
>>> def progress_callback(bytes_consumed, total_bytes):
>>>     '''progress callback
>>> 
>>>     :param int bytes_consumed: Consumed bytes. For upload it's uploaded bytes. for download it is download bytes.
>>>     :param int total_bytes: Total bytes.
>>>     '''
Note that total_bytes has different meanings for download and upload.
  • For upload: If the input is bytes data or file object supports seek/tell, it is the total size. Otherwise it is none.
  • For Download: If http headers that are returned have content-length header, then it is the value of content-length. Otherwise it is none.

Unix Time

OSS Python SDK automatically converts the server time to Unix time (or epoch time, https://en.wikipedia.org/wiki/Unix_time )

The standard time format in OSS is:
  • HTTP Date format, for example Sat, 05 Dec 2015 11:04:39 GMT. It is used in http headers such as If-Modified-Since or Last-Modified.
  • ISO8601 format, for example 2015-12-05T00:00:00.000Z. It is used for lifecycle management configuration, for the create time of a result bucket list, last modified time of a result file list and more.
http_date converts the Unix Time to HTTP Date. http_to_unixtime does the opposite. For example:
>>> import oss2, time
>>> unix_time = int(time.time())             # Current time in UNIX Time, Value is 1449313829
>>> date_str = oss2.http_date(unix_time)     # The date_str will be 'Sat, 05 Dec 2015 11:10:29 GMT'
>>> oss2.http_to_unixtime(date_str)          # The result is 1449313829

Note

Please use http_date instead of strftime to generate the date in http protocol. Because the latter depends on the locale. For example, strftime result could contain Chinese which could not be parsed by OSS server.

iso8601_to_unixtime converts date in ISO8601 format to Unix Time. date_to_iso8601 and iso8601_to_date do the translation between ISO8601 and datetime.date. For example:
>>> import oss2
>>> d = oss2.iso8601_to_date('2015-12-05T00:00:00.000Z')  # Get datetime.date(2015, 12, 5)
>>> date_str = oss2.date_to_iso8601(d)                    # Get '2015-12-05T00:00:00.000Z'
>>> oss2.iso8601_to_unixtime(date_str)                    # Get 1449273600