IBM Cloud Docs
Python の使用

Python の使用

Python は boto3 ライブラリーの fork を通してサポートされ、IBM Cloud® Object Storage を活用するための機能を備えています。

pip install ibm-cos-sdk を使用して、Python Package Index からインストールできます。

ソースコードは以下にあります。GitHub

ibm_boto3 ライブラリーは、IBM Cloud® Object Storage API のすべてにアクセスできます。 以下の基本的な例に示すように、サービス・リソース (下位クライアント) の作成時は、エンドポイント、API キー、およびインスタンス ID を指定しなければなりません。

サービスインスタンスIDは、リソースインスタンスID 。 この値は、サービス資格情報を作成するか、CLI を介して見つけることができます。

詳細なドキュメントは以下をご覧ください。ここ

クライアントの作成と資格情報の入手

COS に接続するために、資格情報 (API キーとサービス・インスタンス ID) を使用してクライアントが作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。

サービス資格情報を生成した後は、結果の JSON 文書を ~/.bluemix/cos_credentials に保存できます。 クライアントの作成時に他の資格情報が明示的に設定されない限り、SDK は、このファイルから資格情報を自動的に入手します。 cos_credentials ファイルに HMAC 鍵が含まれている場合、クライアントは署名を使用して認証を行います。それ以外の場合、クライアントは指定された API 鍵を使用して、ベアラー・トークンを使用して認証を行います (API 鍵を使用するには、クライアント作成時に config=Config(signature_version="oauth") が組み込まれている必要があります)。

AWS S3 からマイグレーションする場合は、~/.aws/credentials から資格情報データを以下の形式で入手することもできます。

[default]
aws_access_key_id = {API_KEY}
aws_secret_access_key = {SERVICE_INSTANCE_ID}

注記: 両方 ~/.bluemix/cos_credentials そして ~/.aws/credentials 存在する、cos_credentials 優先されます。

必要な情報の収集

この後の例には、以下の変数が現れます。

コード例

コード例は、サポートされているリリース・バージョンの Pythonでテストされています。

コードでは、図に示すように、不等号括弧またはその他の余分の文字を削除する必要があります。

構成の初期化

この例では、 resource オブジェクトを作成します。 リソースは、COS へのオブジェクト指向インターフェースを提供します。 これにより、クライアント・オブジェクトによって提供される低レベル呼び出しよりも高いレベルの抽象化が可能になります。

一部の操作 ( Aspera 高速転送など) では、 client オブジェクトが必要であることに注意してください。 Aspera 自体には、 Python バージョン 3.6が必要です。

レガシー通知: Aspera のサポートはレガシーと見なされています。 代わりに、 Aspera Transfer SDK を使用してください。

import ibm_boto3
from ibm_botocore.client import Config, ClientError

# Constants for IBM COS values
COS_ENDPOINT = "<endpoint>" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
COS_API_KEY_ID = "<api-key>" # eg "W00YixxxxxxxxxxMB-odB-2ySfTrFBIQQWanc--P3byk"
COS_INSTANCE_CRN = "<service-instance-id>" # eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003xxxxxxxxxx1c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"

# Create resource
cos_resource = ibm_boto3.resource("s3",
    ibm_api_key_id=COS_API_KEY_ID,
    ibm_service_instance_id=COS_INSTANCE_CRN,
    config=Config(signature_version="oauth"),
    endpoint_url=COS_ENDPOINT
)

クライアントは、COS S3 API への低レベル・インターフェースを提供します。 これにより、ヘッダーまたは XML 応答ペイロードに含まれる情報にアクセスするために、リソースによって提供される抽象化されたメソッドおよび属性を利用するのではなく、HTTP 応答を直接処理することができます。


import ibm_boto3
from ibm_botocore.client import Config, ClientError

# Constants for IBM COS values
COS_ENDPOINT = "<endpoint>" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
COS_API_KEY_ID = "<api-key>" # eg "W00YixxxxxxxxxxMB-odB-2ySfTrFBIQQWanc--P3byk"
COS_INSTANCE_CRN = "<service-instance-id>" # eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003xxxxxxxxxx1c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"

# Create client
cos_client = ibm_boto3.client("s3",
    ibm_api_key_id=COS_API_KEY_ID,
    ibm_service_instance_id=COS_INSTANCE_CRN,
    config=Config(signature_version="oauth"),
    endpoint_url=COS_ENDPOINT
)

キー値

  • <endpoint>- クラウドのパブリックエンドポイントObject Storageスキーマのプレフィックス(' https://')(から入手可能)IBM Cloudダッシュボード)。 エンドポイントについて詳しくは、エンドポイントおよびストレージ・ロケーションを参照してください。
  • <api-key>- サービス資格情報を作成するときに生成された API キー (作成および削除の例には書き込みアクセスが必要です)
  • <service-instance-id>- クラウドのリソースIDObject Storage(以下から入手可能)IBM Cloudコマンドライン または IBM Cloudダッシュボード
  • <location>- クラウドのデフォルトの場所Object Storage(使用される地域と一致する必要があります <endpoint>

SDK リファレンス

新規バケットの作成

以下の例では、低レベル・インターフェースであるクライアントを使用しています。

LocationConstraint の有効なプロビジョニング・コードのリストについては、ストレージ・クラスのガイドを参照してください。

def create_bucket(bucket_name):
    print("Creating new bucket: {0}".format(bucket_name))
    try:
        cos_client.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                "LocationConstraint":COS_BUCKET_LOCATION
            }
        )
        print("Bucket: {0} created!".format(bucket_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to create bucket: {0}".format(e))

SDK リファレンス

方法

新規テキスト・ファイルの作成

def create_text_file(bucket_name, item_name, file_text):
    print("Creating new item: {0}".format(item_name))
    try:
        cos_client.put_object(
            Bucket=bucket_name,
            Key=item_name,
            Body=file_text
        )
        print("Item: {0} created!".format(item_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to create text file: {0}".format(e))

SDK リファレンス

方法

使用可能なバケットのリスト

def get_buckets():
    print("Retrieving list of buckets")
    try:
        buckets = cos_client.list_buckets()
        for bucket in buckets["Buckets"]:
            print("Bucket Name: {0}".format(bucket["Name"]))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to retrieve list buckets: {0}".format(e))

SDK リファレンス

方法

バケット内の項目のリスト

def get_bucket_contents(bucket_name):
    print("Retrieving bucket contents from: {0}".format(bucket_name))
    try:
        files = cos_client.list_objects(Bucket=bucket_name)
        for file in files.get("Contents", []):
            print("Item: {0} ({1} bytes).".format(file["Key"], file["Size"]))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to retrieve bucket contents: {0}".format(e))

SDK リファレンス

方法

特定の項目のファイル内容の取得

def get_item(bucket_name, item_name):
    print("Retrieving item from bucket: {0}, key: {1}".format(bucket_name, item_name))
    try:
        file = cos_client.get_object(Bucket=bucket_name, Key=item_name)
        print("File Contents: {0}".format(file["Body"].read()))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to retrieve file contents: {0}".format(e))

SDK リファレンス

方法

バケットから項目を削除

def delete_item(bucket_name, object_name):
    try:
        cos_client.delete_object(Bucket=bucket_name, Key=object_name)
        print("Item: {0} deleted!\n".format(object_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to delete object: {0}".format(e))

SDK リファレンス

方法

バケットから複数項目を削除

削除要求には、削除するキーを最大 1000 個含めることができます。 これはリクエストごとのパフォーマンスの低下を軽減するのに役立ちますが、多数のキーを削除する場合には注意してください。 また、適切なパフォーマンスを確保するために、オブジェクトのサイズも考慮に入れてください。

def delete_items(bucket_name):
    try:
        delete_request = {
            "Objects": [
                { "Key": "deletetest/testfile1.txt" },
                { "Key": "deletetest/testfile2.txt" },
                { "Key": "deletetest/testfile3.txt" },
                { "Key": "deletetest/testfile4.txt" },
                { "Key": "deletetest/testfile5.txt" }
            ]
        }

        response = cos_client.delete_objects(
            Bucket=bucket_name,
            Delete=delete_request
        )

        print("Deleted items for {0}\n".format(bucket_name))
        print(json.dumps(response.get("Deleted"), indent=4))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to copy item: {0}".format(e))

SDK リファレンス

方法

バケットの削除

def delete_bucket(bucket_name):
    print("Deleting bucket: {0}".format(bucket_name))
    try:
        cos_client.delete_bucket(Bucket=bucket_name)
        print("Bucket: {0} deleted!".format(bucket_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to delete bucket: {0}".format(e))

SDK リファレンス

方法

バケット名は削除後 10 ~ 15 分間予約されます。

複数パーツ・アップロードの実行

バイナリー・ファイルのアップロード (推奨される方法)

upload_fileobj方法のS3オブジェクトは必要に応じて自動的にマルチパートアップロードを実行します。 の TransferConfigクラスは、マルチパートアップロードを使用するためのしきい値を決定するために使用されます。

def multi_part_upload(bucket_name, item_name, file_path):
    try:
        print("Starting file transfer for {0} to bucket: {1}\n".format(item_name, bucket_name))
        # set 5 MB chunks
        part_size = 1024 * 1024 * 5

        # set threadhold to 15 MB
        file_threshold = 1024 * 1024 * 15

        # set the transfer threshold and chunk size
        transfer_config = ibm_boto3.s3.transfer.TransferConfig(
            multipart_threshold=file_threshold,
            multipart_chunksize=part_size
        )

        # the upload_fileobj method will automatically execute a multi-part upload
        # in 5 MB chunks for all files over 15 MB
        with open(file_path, "rb") as file_data:
            cos_client.upload_fileobj(
                Bucket=bucket_name,
                Key=item_name,
                Fileobj=file_data,
                Config=transfer_config
            )

        print("Transfer for {0} Complete!\n".format(item_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to complete multi-part upload: {0}".format(e))

SDK リファレンス

方法

手動での複数パーツ・アップロードの実行

必要に応じて、S3.Clientクラスを使用して、マルチパートアップロードを実行できます。 これは、アップロード・プロセスをより正確に制御する必要がある場合に役立つ可能性があります。

def multi_part_upload_manual(bucket_name, item_name, file_path):
    try:
        # create client object
        cos_client = ibm_boto3.client("s3",
            ibm_api_key_id=COS_API_KEY_ID,
            ibm_service_instance_id=COS_SERVICE_CRN,
            config=Config(signature_version="oauth"),
            endpoint_url=COS_ENDPOINT
        )

        print("Starting multi-part upload for {0} to bucket: {1}\n".format(item_name, bucket_name))

        # initiate the multi-part upload
        mp = cos_client.create_multipart_upload(
            Bucket=bucket_name,
            Key=item_name
        )

        upload_id = mp["UploadId"]

        # min 20MB part size
        part_size = 1024 * 1024 * 20
        file_size = os.stat(file_path).st_size
        part_count = int(math.ceil(file_size / float(part_size)))
        data_packs = []
        position = 0
        part_num = 0

        # begin uploading the parts
        with open(file_path, "rb") as file:
            for i in range(part_count):
                part_num = i + 1
                part_size = min(part_size, (file_size - position))

                print("Uploading to {0} (part {1} of {2})".format(item_name, part_num, part_count))

                file_data = file.read(part_size)

                mp_part = cos_client.upload_part(
                    Bucket=bucket_name,
                    Key=item_name,
                    PartNumber=part_num,
                    Body=file_data,
                    ContentLength=part_size,
                    UploadId=upload_id
                )

                data_packs.append({
                    "ETag":mp_part["ETag"],
                    "PartNumber":part_num
                })

                position += part_size

        # complete upload
        cos_client.complete_multipart_upload(
            Bucket=bucket_name,
            Key=item_name,
            UploadId=upload_id,
            MultipartUpload={
                "Parts": data_packs
            }
        )
        print("Upload for {0} Complete!\n".format(item_name))
    except ClientError as be:
        # abort the upload
        cos_client.abort_multipart_upload(
            Bucket=bucket_name,
            Key=item_name,
            UploadId=upload_id
        )
        print("Multi-part upload aborted for {0}\n".format(item_name))
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to complete multi-part upload: {0}".format(e))

SDK リファレンス (続き)

クラス

方法

TransferManager を使用したラージ・オブジェクトのアップロード

TransferManager は、必要に応じて構成パラメーターを設定して自動的に複数パーツ・アップロードを取り込むことで、大規模ファイル転送を実行するための新しい方法を提供します。

def upload_large_file(bucket_name, item_name, file_path):
    print("Starting large file upload for {0} to bucket: {1}".format(item_name, bucket_name))

    # set the chunk size to 5 MB
    part_size = 1024 * 1024 * 5

    # set threadhold to 5 MB
    file_threshold = 1024 * 1024 * 5

    # Create client connection
    cos_client = ibm_boto3.client("s3",
        ibm_api_key_id=COS_API_KEY_ID,
        ibm_service_instance_id=COS_SERVICE_CRN,
        config=Config(signature_version="oauth"),
        endpoint_url=COS_ENDPOINT
    )

    # set the transfer threshold and chunk size in config settings
    transfer_config = ibm_boto3.s3.transfer.TransferConfig(
        multipart_threshold=file_threshold,
        multipart_chunksize=part_size
    )

    # create transfer manager
    transfer_mgr = ibm_boto3.s3.transfer.TransferManager(cos_client, config=transfer_config)

    try:
        # initiate file upload
        future = transfer_mgr.upload(file_path, bucket_name, item_name)

        # wait for upload to complete
        future.result()

        print ("Large file upload complete!")
    except Exception as e:
        print("Unable to complete large file upload: {0}".format(e))
    finally:
        transfer_mgr.shutdown()

バケット内の項目のリスト (v2)

S3.Client オブジェクトには、内容をリストするための更新されたメソッドがあります (list_objects_v2)。 このメソッドでは、返されるレコードの数を制限できるほか、レコードをバッチで取得できます。 これは、アプリケーション内で結果をページングする場合に役立ち、パフォーマンスも改善される可能性があります。

def get_bucket_contents_v2(bucket_name, max_keys):
    print("Retrieving bucket contents from: {0}".format(bucket_name))
    try:
        # create client object
        cos_client = ibm_boto3.client("s3",
            ibm_api_key_id=COS_API_KEY_ID,
            ibm_service_instance_id=COS_SERVICE_CRN,
            config=Config(signature_version="oauth"),
            endpoint_url=COS_ENDPOINT)

        more_results = True
        next_token = ""

        while (more_results):
            response = cos_client.list_objects_v2(Bucket=bucket_name, MaxKeys=max_keys, ContinuationToken=next_token)
            files = response["Contents"]
            for file in files:
                print("Item: {0} ({1} bytes).".format(file["Key"], file["Size"]))

            if (response["IsTruncated"]):
                next_token = response["NextContinuationToken"]
                print("...More results in next batch!\n")
            else:
                more_results = False
                next_token = ""

    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to retrieve bucket contents: {0}".format(e))

SDK リファレンス

方法

Key Protect の使用

クラウド内の重要な Data at Rest (保存されたデータ) を暗号化するために、Key Protect をストレージ・バケットに追加できます。

開始前に

Key-Protect が有効なバケットを作成するためには、以下の項目が必要です。

ルート・キー CRN の取得

  1. Key Protect サービスのインスタンス ID を取得します。
  2. Key Protect API を使用して、すべての使用可能なキーを取得します。
    • curl コマンドまたは API REST クライアント (Postman など) のいずれかを使用して、Key Protect API にアクセスできます。
  3. バケットで Key Protect を有効にするために使用するルート・キーの CRN を取得します。 CRN は、下記のようになります。

crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234

Key Protect が有効なバケットの作成

COS_KP_ALGORITHM = "<algorithm>"
COS_KP_ROOTKEY_CRN = "<root-key-crn>"

# Create a new bucket with key protect (encryption)
def create_bucket_kp(bucket_name):
    print("Creating new encrypted bucket: {0}".format(bucket_name))
    try:
        cos_client.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                "LocationConstraint":COS_BUCKET_LOCATION
            },
            IBMSSEKPEncryptionAlgorithm=COS_KP_ALGORITHM,
            IBMSSEKPCustomerRootKeyCrn=COS_KP_ROOTKEY_CRN
        )
        print("Encrypted Bucket: {0} created!".format(bucket_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to create encrypted bucket: {0}".format(e))

キー値

  • <algorithm>- バケットに追加された新しいオブジェクトに使用される暗号化アルゴリズム(デフォルトはAES256 )。
  • <root-key-crn>- ルートキーのCRNは、Key Protectサービス。

SDK リファレンス

方法

Aspera 高速転送の使用

レガシー通知: Aspera のサポートはレガシーと見なされています。 Aspera Transfer SDK[https://developer.ibm.com/apis/catalog/aspera--aspera-transfer-sdk/API Reference]を使用することをお勧めします。

レガシー通知: Aspera のサポートはレガシーと見なされています。 ユーザーは、 Aspera Transfer SDKを使用することをお勧めします。

Aspera 高速転送ライブラリーをインストールすると、アプリケーション内で高速ファイル転送を使用できます。 Aspera ライブラリーはクローズ・ソースであるため、(Apache ライセンスを使用する) COS SDK のオプションの依存関係です。

各 Aspera セッションは、転送を実行するためにクライアント・マシン上で実行される個別の ascp プロセスを作成します。 ご使用のコンピューティング環境でこのプロセスの実行が許可されるようにしてください。

AsperaTransferManager の初期化

初期化する前に AsperaTransferManager、動作していることを確認してください clientresource または session) 物体。

import ibm_boto3
from ibm_botocore.client import Config
from ibm_s3transfer.aspera.manager import AsperaTransferManager

COS_ENDPOINT = "<endpoint>" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
COS_API_KEY_ID = "<api-key>"
COS_RESOURCE_CRN = "<resource-instance-id>"
COS_BUCKET_LOCATION = "<location>"

# Create resource
cos_client = ibm_boto3.client("s3",
    ibm_api_key_id=COS_API_KEY_ID,
    ibm_service_instance_id=COS_RESOURCE_CRN,
    config=Config(signature_version="oauth"),
    endpoint_url=COS_ENDPOINT
)

transfer_manager = AsperaTransferManager(cos)

Aspera 高速転送用の IAM API キーを指定する必要があります。 HMAC 資格情報 は現在サポート されていません。 IAM について詳しくは、 ここをクリックしてください。

スループットを最大にするには、しきい値で定義したサイズのデータをチャンクで送信する、指定した数の並列セッションに転送を分割します。

マルチセッションを使用する場合の標準的な構成は、以下のとおりです。

  • 2500 MBps ターゲット・レート
  • 100 MB のしきい値 (これが、ほとんどのアプリケーションに対する推奨値です)
ms_transfer_config = AsperaConfig(multi_session="all",
                                  target_rate_mbps=2500,
                                  multi_session_threshold_mb=100)

上記の例の場合、SDK は 2500 MBps のターゲット・レートに到達しようと、それに見合った十分な数のセッションを作成します。

セッション管理を SDK で明示的に構成することもできます。 これは、ネットワーク使用率をより正確に制御する必要がある場合に役立ちます。

明示的なマルチセッションを使用する場合の標準的な構成は、以下のとおりです。

  • 2 個または 10 個のセッション
  • 100 MB のしきい値 (これが、ほとんどのアプリケーションに対する推奨値です)
from ibm_s3transfer.aspera.manager import AsperaConfig
# Configure 2 sessions for transfer
ms_transfer_config = AsperaConfig(multi_session=2,
                                  multi_session_threshold_mb=100)

# Create the Aspera Transfer Manager
transfer_manager = AsperaTransferManager(client=client,
                                         transfer_config=ms_transfer_config)

ほとんどのシナリオで最高のパフォーマンスを得るには、複数のセッションを常に使用して、インスタンス化に関連する処理を最小限に抑えます。Aspera高速転送。 ネットワーク容量が 1 Gbps 以上ある場合は、10 個のセッションを使用してください。 それより低い帯域幅のネットワークでは、使用するセッションを 2 つにする必要があります。

ファイルのアップロード

bucket_name = "<bucket-name>"
upload_filename = "<absolute-path-to-file>"
object_name = "<item-name>"

# Create Transfer manager
with AsperaTransferManager(client) as transfer_manager:

    # Perform upload
    future = transfer_manager.upload(upload_filename, bucket_name, object_name)

    # Wait for upload to complete
    future.result()

キー値

  • <bucket-name>- ターゲットバケットの名前
  • <absolute-path-to-file>- アップロードするファイルのディレクトリパスとファイル名
  • <item-name>- バケットに追加された新しいファイルの名前

ファイルのダウンロード

bucket_name = "<bucket-name>"
download_filename = "<absolute-path-to-file>"
object_name = "<object-to-download>"

# Create Transfer manager
with AsperaTransferManager(client) as transfer_manager:

    # Get object with Aspera
    future = transfer_manager.download(bucket_name, object_name, download_filename)

    # Wait for download to complete
    future.result()

キー値

  • <bucket-name>- バケットの名前Object StorageサービスインスタンスにはAspera有効になりました。
  • <absolute-path-to-file>- ローカル システムにファイルを保存するディレクトリとファイル名。
  • <object-to-download>- ダウンロードするバケット内のファイルの名前。

ディレクトリーのアップロード

bucket_name = "<bucket-name>"
# THIS DIRECTORY MUST EXIST LOCALLY, and have objects in it.
local_upload_directory = "<absolute-path-to-directory>"
# THIS SHOULD NOT HAVE A LEADING "/"
remote_directory = "<object prefix>"

# Create Transfer manager
with AsperaTransferManager(client) as transfer_manager:

    # Perform upload
    future = transfer_manager.upload_directory(local_upload_directory, bucket_name, remote_directory)

    # Wait for upload to complete
    future.result()

キー値

  • <bucket-name>- バケットの名前Object StorageサービスインスタンスにはAspera有効
  • <absolute-path-to-directory>- アップロードするファイルが含まれるローカル ディレクトリ。 前後に / を付ける必要があります (例: /Users/testuser/Documents/Upload/)
  • <object prefix>- ファイルを保存するバケット内のディレクトリの名前。 前にスラッシュ / は付けないでください (例: newuploads/)

ディレクトリーのダウンロード

bucket_name = "<bucket-name>"
# THIS DIRECTORY MUST EXIST LOCALLY
local_download_directory = "<absolute-path-to-directory>"
remote_directory = "<object prefix>"

# Create Transfer manager
with AsperaTransferManager(client) as transfer_manager:

    # Get object with Aspera
    future = transfer_manager.download_directory(bucket_name, remote_directory, local_download_directory)

    # Wait for download to complete
    future.result()

キー値

  • <bucket-name>- バケットの名前Object StorageサービスインスタンスにはAspera有効
  • <absolute-path-to-directory>- ダウンロードしたファイルを保存するローカル ディレクトリ。 先頭と末尾にスラッシュが必要です /(あれは /Users/testuser/Downloads/
  • <object prefix>- ファイルを保存するバケット内のディレクトリの名前。 前にスラッシュ / は付けないでください (例: todownload/)

サブスクライバーの使用

サブスクライバーは、カスタム・コールバック・メソッドを関連付けることにより、転送を監視できます。 すべての転送は、以下のフェーズの間を遷移します。

Queued - In Progress - Done

各フェーズに応じた 3 つの使用可能なサブスクライバーがあります。

  • CallbackOnQueued() - 新しい転送が AsperaTransferManager に追加されたときに呼び出されます。
  • CallbackOnProgress() - 転送がデータを送信したときに呼び出されます (転送の進行中は繰り返し起動されます)。
  • CallbackOnDone() - 転送が完了すると呼び出されます。
bucket_name = "<bucket-name>"
local_download_directory = "<absolute-path-to-directory>"
remote_directory = "<object prefix>"

# Subscriber callbacks
class CallbackOnQueued(AsperaBaseSubscriber):
    def __init__(self):
        pass

    def on_queued(self, future, **kwargs):
        print("Directory download queued.")

class CallbackOnProgress(AsperaBaseSubscriber):
    def __init__(self):
        pass

    def on_progress(self, future, bytes_transferred, **kwargs):
        print("Directory download in progress: %s bytes transferred" % bytes_transferred)

class CallbackOnDone(AsperaBaseSubscriber):
    def __init__(self):
        pass

    def on_done(self, future, **kwargs):
        print("Downloads complete!")

# Create Transfer manager
transfer_manager = AsperaTransferManager(client)

# Attach subscribers
subscribers = [CallbackOnQueued(), CallbackOnProgress(), CallbackOnDone()]

# Get object with Aspera
future = transfer_manager.download_directory(bucket_name, remote_directory, local_download_directory, None, subscribers)

# Wait for download to complete
future.result()

キー値

  • <bucket-name>- バケットの名前Object StorageサービスインスタンスにはAspera有効
  • <absolute-path-to-directory>- ダウンロードしたファイルを保存するローカル ディレクトリ。 前後にスラッシュ / を付ける必要があります (例: /Users/testuser/Downloads/)
  • <object prefix>- ファイルを保存するバケット内のディレクトリの名前。 前にスラッシュ / は付けないでください (例: todownload/)

上記のサンプル・コードによって、以下のような出力が生成されます。

Directory download queued.
Directory download in progress: 5632 bytes transferred
Directory download in progress: 1047552 bytes transferred
...
Directory download in progress: 53295130 bytes transferred
Directory download in progress: 62106855 bytes transferred
Download complete!

一時停止/再開/キャンセル

SDK には、AsperaTransferFuture オブジェクトの以下のメソッドを使用して、ファイル/ディレクトリー転送の進行を管理できる機能があります。

  • pause()
  • resume()
  • cancel()

上で概略が説明されているどのメソッドを呼び出しても副次作用はありません。 クリーンアップとハウスキーピングは、SDK によって適切に処理されます。

# Create Transfer manager
bucket_name = "<bucket-name>"
local_download_directory = "<absolute-path-to-directory>"
remote_directory = "<object prefix>"

with AsperaTransferManager(client) as transfer_manager:

    # download a directory with Aspera
    future = transfer_manager.download_directory(bucket_name, remote_directory, local_download_directory, None, None)

    # pause the transfer
    future.pause()

    # resume the transfer
    future.resume()

    # cancel the transfer
    future.cancel()

Aspera に関する問題のトラブルシューティング

問題: 3.6 以外の任意のバージョンの Python を使用する開発者は、 Aspera SDKのインストール時または使用時に障害が発生する可能性があります。

原因: 異なるバージョンがある場合Pythonお使いの環境にインストールされていない場合は、インストール時にインストールエラーが発生する可能性があります。Aspera SDK 。 この原因は、パスに DLL ファイルが欠落しているか、パスに誤った DLL が含まれているためです。

解決策: この問題を解決するための最初のステップは、Aspera ライブラリーを再インストールすることです。 インストール中に障害が発生した可能性があります。 その結果、DLL ファイルが影響を受けた可能性があります。 それでも問題が解決しない場合は、Python のバージョンを更新する必要があります。 これができない場合は、インストールを使用できます インテル® ディストリビューションPython*。 これにより、問題なく Aspera SDK を Python 3.6.x にインストールできます。

メタデータの更新

既存のオブジェクトのメタデータを更新する方法は、2 とおりあります。

  • 新しいメタデータと元のオブジェクト・コンテンツが指定された PUT 要求
  • 元のオブジェクトをコピー・ソースとして指定し、新しいメタデータを使用する COPY 要求の実行

PUT を使用したメタデータの更新

注記:PUT リクエストはオブジェクトの既存の内容を上書きするため、最初にダウンロードして、新しいメタデータで再アップロードする必要があります。

def update_metadata_put(bucket_name, item_name, key, value):
    try:
        # retrieve the existing item to reload the contents
        response = cos_client.get_object(Bucket=bucket_name, Key=item_name)
        existing_body = response.get("Body").read()

        # set the new metadata
        new_metadata = {
            key: value
        }

        cos_client.put_object(Bucket=bucket_name, Key=item_name, Body=existing_body, Metadata=new_metadata)

        print("Metadata update (PUT) for {0} Complete!\n".format(item_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        log_error("Unable to update metadata: {0}".format(e))

COPY を使用したメタデータの更新

def update_metadata_copy(bucket_name, item_name, key, value):
    try:
        # set the new metadata
        new_metadata = {
            key: value
        }

        # set the copy source to itself
        copy_source = {
            "Bucket": bucket_name,
            "Key": item_name
        }

        cos_client.copy_object(Bucket=bucket_name, Key=item_name, CopySource=copy_source, Metadata=new_metadata, MetadataDirective="REPLACE")

        print("Metadata update (COPY) for {0} Complete!\n".format(item_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        log_error("Unable to update metadata: {0}".format(e))

Immutable Object Storage の使用

既存のバケットへの保護構成の追加

保護対象のバケットに書き込まれたオブジェクトは、保護期間が満了し、オブジェクトに対するすべての法的保留が解除されるまで削除できません。 オブジェクトの作成時にオブジェクト固有の値が指定されない限り、バケットのデフォルトの保存期間値がオブジェクトにも適用されます。 保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

保存期間設定でサポートされる最小値と最大値 MinimumRetentionDefaultRetention 、 そして MaximumRetention 最小値は 0 日、最大値は 365243 日 (1000 年) です。

def add_protection_configuration_to_bucket(bucket_name):
    try:
        new_protection_config = {
            "Status": "Retention",
            "MinimumRetention": {"Days": 10},
            "DefaultRetention": {"Days": 100},
            "MaximumRetention": {"Days": 1000}
        }

        cos_client.put_bucket_protection_configuration(Bucket=bucket_name, ProtectionConfiguration=new_protection_config)

        print("Protection added to bucket {0}\n".format(bucket_name))
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to set bucket protection config: {0}".format(e))

バケットに対する保護のチェック

def get_protection_configuration_on_bucket(bucket_name):
    try:
        response = cos_client.get_bucket_protection_configuration(Bucket=bucket_name)
        protection_config = response.get("ProtectionConfiguration")

        print("Bucket protection config for {0}\n".format(bucket_name))
        print(protection_config)
        print("\n")
    except ClientError as be:
        print("CLIENT ERROR: {0}\n".format(be))
    except Exception as e:
        print("Unable to get bucket protection config: {0}".format(e))

保護オブジェクトのアップロード

保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

タイプ 説明
Retention-Period 負でない整数 (秒数) オブジェクトを保管する保存期間 (秒数)。 オブジェクトは、保存期間に指定された時間が経過するまで上書きも削除もできません。 このフィールドと Retention-Expiration-Date が指定された場合、400 エラーが返されます。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。 ゼロ (0) は有効な値であり、バケットの最小保存期間も 0 であると想定されます。
Retention-expiration-date 日付 (ISO 8601 フォーマット) オブジェクトを合法的に削除または変更できるようになる日付。 これか Retention-Period ヘッダーのいずれかのみを指定できます。 両方が指定された場合は、400 エラーが返されます。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。
Retention-legal-hold-id ストリング オブジェクトに適用される単一の法的保留。 法的保留とは、Y 文字の長さのストリングです。 オブジェクトに関連付けられたすべての法的保留が解除されるまで、オブジェクトは上書きも削除もできません。
def put_object_add_legal_hold(bucket_name, object_name, file_text, legal_hold_id):
    print("Add legal hold {0} to {1} in bucket {2} with a putObject operation.\n".format(legal_hold_id, object_name, bucket_name))
    cos_client.put_object(
        Bucket=bucket_name,
        Key=object_name,
        Body=file_text,
        RetentionLegalHoldId=legal_hold_id)
    print("Legal hold {0} added to object {1} in bucket {2}\n".format(legal_hold_id, object_name, bucket_name))

def copy_protected_object(source_bucket_name, source_object_name, destination_bucket_name, new_object_name):
    print("Copy protected object {0} from bucket {1} to {2}/{3}.\n".format(source_object_name, source_bucket_name, destination_bucket_name, new_object_name))

    copy_source = {
        "Bucket": source_bucket_name,
        "Key": source_object_name
    }

    cos_client.copy_object(
        Bucket=destination_bucket_name,
        Key=new_object_name,
        CopySource=copy_source,
        RetentionDirective="Copy"
    )

    print("Protected object copied from {0}/{1} to {2}/{3}\n".format(source_bucket_name, source_object_name, destination_bucket_name, new_object_name));

def complete_multipart_upload_with_retention(bucket_name, object_name, upload_id, retention_period):
    print("Completing multi-part upload for object {0} in bucket {1}\n".format(object_name, bucket_name))
    cos_client.complete_multipart_upload(
        Bucket=bucket_name,
        Key=object_name,
        MultipartUpload={
            "Parts":[{
                "ETag": part["ETag"],
                "PartNumber": 1
            }]
        },
        UploadId=upload_id,
        RetentionPeriod=retention_period
    )

    print("Multi-part upload completed for object {0} in bucket {1}\n".format(object_name, bucket_name))

def upload_file_with_retention(bucket_name, object_name, path_to_file, retention_period):
    print("Uploading file {0} to object {1} in bucket {2}\n".format(path_to_file, object_name, bucket_name))

    args = {
        "RetentionPeriod": retention_period
    }

    cos_client.upload_file(
        Filename=path_to_file,
        Bucket=bucket_name,
        Key=object_name,
        ExtraArgs=args
    )

    print("File upload complete to object {0} in bucket {1}\n".format(object_name, bucket_name))

保護オブジェクトの保存期間の延長

オブジェクトの保存期間は延長のみが可能です。 現在構成されている値から減らすことはできません。

保存延長値は次の 3 つの方法のいずれかで設定されます。

  • 現行値からの追加時間 (Additional-Retention-Period または同様のメソッド)
  • 新しい延長期間 (秒数) (Extend-Retention-From-Current-Time または同様のメソッド)
  • オブジェクトの新しい保存有効期限日付 (New-Retention-Expiration-Date または同様のメソッド)

オブジェクト・メタデータに保管されている現在の保存期間は、extendRetention 要求に設定されているパラメーターに応じて、指定された追加時間分増やされるか、新しい値に置き換えられます。 いずれの場合も、保存延長パラメーターは現在の保存期間に対して検査され、更新後の保存期間が現在の保存期間より大きい場合にのみ、延長パラメーターが受け入れられます。

保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

def extend_retention_period_on_object(bucket_name, object_name, additional_seconds):
    print("Extend the retention period on {0} in bucket {1} by {2} seconds.\n".format(object_name, bucket_name, additional_seconds))

    cos_client.extend_object_retention(
        Bucket=bucket_ame,
        Key=object_name,
        AdditionalRetentionPeriod=additional_seconds
    )

    print("New retention period on {0} is {1}\n".format(object_name, additional_seconds))

保護オブジェクトの法的保留のリスト

この操作で返される内容は以下のとおりです。

  • オブジェクト作成日
  • オブジェクト保存期間 (秒数)
  • 期間および作成日に基づいて計算された保存有効期限
  • 法的保留のリスト
  • 法的保留 ID
  • 法的保留が適用されたときのタイム・スタンプ

オブジェクトに法的保留がない場合は、空の LegalHoldSet が返されます。 オブジェクトに保存期間が指定されていない場合、 404 エラーが返されます。

def list_legal_holds_on_object(bucket_name, object_name):
    print("List all legal holds on object {0} in bucket {1}\n".format(object_name, bucket_name));

    response = cos_client.list_legal_holds(
        Bucket=bucket_name,
        Key=object_name
    )

    print("Legal holds on bucket {0}: {1}\n".format(bucket_name, response))

ホストされた静的 Web サイトの作成

通常、バケット所有者のみが静的 Web サイトをホストするようにバケットを構成することを許可されるため、この操作には許可が必要です。 これらのパラメーターは、サイトへの訪問者のデフォルトの接尾部と、オプションのエラー文書を決定します。

def putBucketWebsiteConfiguration(bucket_name):
    website_defaults = {
        'ErrorDocument': {'Key': 'error.html'},
        'IndexDocument': {'Suffix': 'index.html'},
    }
    cos_client.put_bucket_website(Bucket=bucket_name, WebsiteConfiguration=website_defaults)
    print("Website configuration set on bucket {0}\n".format(bucket_name))

次のステップ

詳しくは、 GitHubでソース・コードを参照してください。