QingStor 对象存储的新版 Python SDK,已在 GitHub 开源。本文为简要使用文档,更多详细信息请参见 GitHub 项目 和 Python SDK API 文档。

Python SDK 使用 Snips 工具生成,各接口的调用均与 QingStor 对象存储的 API 相对应。其返回码、请求头、错误码等规定请参照具体的 Qingstor API 文档。

使用 SDK 之前请先在 青云QingCloud 管理控制台 申请 Access key。

安装

qingstor-sdk 自 v2.3.0 后,仅支持 python v3.6 及以上的版本。

故,安装 qingstor-sdk 时,需确认当前环境中的 python 版本是否满足要求。若 python 版本低于 v3.6,则在使用该 SDK 的过程中,会出错。

使用 Pip 安装:

pip install qingstor-sdk

初始化服务

发起请求前需要初始化服务。以下代码初始化了一个 QingStor Service。

from qingstor.sdk.service.qingstor import QingStor
from qingstor.sdk.config import Config

config = Config('ACCESS_KEY_ID_EXAMPLE', 'SECRET_ACCESS_KEY_EXAMPLE')
qingstor = QingStor(config)

代码示例

  1. 获取账户下的 Bucket 列表

    # List all buckets.
    output = qingstor.list_buckets()
    
    # Print HTTP status code.
    print(output.status_code)
    
    # Print the buckets.
    print(output['buckets'])
  2. 初始化并创建 Bucket。用户需要指定 Bucket 名称和所在 Zone:

    bucket = qingstor.Bucket('test-bucket', 'pek3a')
    output = bucket.put()
  3. 获取 Bucket 中存储的 Object 列表

    output = bucket.list_objects()
    
    # Print the HTTP status code.
    # Example: 200
    print(output.status_code)
    
    # Print the key count.
    # Example: 7
    print(output['keys'])
  4. 上传一个 Object

    with open('/tmp/sdk_bin', 'rb') as f:
        output = bucket.put_object(
            'example_key', body=f
        )
    
    # Print the HTTP status code.
    # Example: 201
    print(output.status_code)
  5. 删除一个 Object

    output = bucket.delete_object('example_key')
    
    # Print the HTTP status code.
    # Example: 204
    print(output.status_code)
  6. 设置 Bucket ACL

    output = bucket.put_acl(acl=[
        {
            'grantee': {
                'type': 'group',
                'name': 'QS_ALL_USERS'
            },
            'permission': 'FULL_CONTROL'
        }
    ])
    
    # Print the HTTP status code.
    # Example: 200
    print(output.status_code)