すべてのプロダクト
Search
ドキュメントセンター

:初期化

最終更新日:Feb 05, 2025

このトピックでは、Python用のObject Storage Service (OSS) SDKを初期化する方法について説明します。

使用上の注意

  • OSS SDK for Pythonを初期化する前に、アクセス資格情報を設定する必要があります。 このトピックでは、アクセス資格情報は環境変数から取得します。 詳細については、「アクセス資格情報の設定」をご参照ください。

  • OSSリージョンとエンドポイントに関する情報を取得する場合は、「リージョンとエンドポイント」をご参照ください。

  • RAMユーザーのAccessKeyペアを作成する場合は、「AccessKeyペアの作成」をご参照ください。

  • OSS SDK for Pythonのほとんどの操作は、oss2.Serviceクラスとoss2.Bucketクラスに基づいて実行されます。

    • oss2.Serviceクラスは、バケットの一覧表示に使用されます。

    • oss2.Bucketクラスは、オブジェクトのアップロード、ダウンロード、削除、およびバケットの設定に使用されます。

    oss2.Serviceクラスとoss2.Bucketクラスを初期化するときは、バケットが配置されているリージョンのエンドポイントを指定する必要があります。 oss2.Serviceクラスは、バケットにマップされたカスタムドメイン名を使用したバケットへのアクセスをサポートしていません。

前提条件

警告

クライアントを設定する前に、RAMユーザーのAccessKeyペアを使用して環境変数を設定しています。

Linux

  1. CLIで次のコマンドを実行して、環境変数の設定を ~/.bashrcファイルに追加します。

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
  2. 次のコマンドを実行して変更を適用します。

    source ~/.bashrc
  3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

macOS

  1. ターミナルで次のコマンドを実行して、デフォルトのシェルタイプを表示します。

    echo $SHELL
  2. デフォルトのシェルタイプに基づいて環境変数を設定します。

    Zsh

    1. 次のコマンドを実行して、環境変数の設定を ~/.zshrcファイルに追加します。

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
    2. 次のコマンドを実行して変更を適用します。

      source ~/.zshrc
    3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    バッシュ

    1. 次のコマンドを実行して、環境変数の設定を ~/.bash_profileファイルに追加します。

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
    2. 次のコマンドを実行して変更を適用します。

      source ~/.bash_profile
    3. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. CMDで次のコマンドを実行します。

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. PowerShellで次のコマンドを実行します。

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. 次のコマンドを実行して、環境変数が有効かどうかを確認します。

    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

デフォルトの例

このセクションでは、V4署名アルゴリズムとV1署名アルゴリズムを使用してOSS SDK for Pythonを初期化する方法の例を示します。

次のサンプルコードでは、バケットのパブリックエンドポイントとRAMユーザーのAccessKeyペアを使用しています。

(推奨) V4署名アルゴリズムの使用

重要
  • V4署名アルゴリズムを使用してOSS SDK for Pythonを初期化する場合、エンドポイントを指定する必要があります。 この例では、中国 (杭州) リージョンのパブリックエンドポイント https://oss-cn-hangzhou.aliyuncs.com が使用されます。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 他のリージョンのパブリックエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。

  • V4署名アルゴリズムを使用する場合、リクエストが開始されるリージョンの識別子としてAlibaba CloudリージョンIDを指定する必要があります。 この例では、中国 (杭州) リージョンのリージョンID cn-hangzhouが使用されています。 他のリージョンのリージョンIDの詳細については、「リージョンとエンドポイント」をご参照ください。

次のサンプルコードは、OSSエンドポイントを使用してV4署名アルゴリズムを使用してOSS SDK for Pythonを初期化する方法の例を示しています。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region) 

(非推奨) V1署名アルゴリズムの使用

重要

2025年3月1日以降、新しいUIDを持つ新規顧客は、OSSのV1署名アルゴリズムを利用できなくなります。 2025年9月1日以降、OSSはV1署名アルゴリズムを更新および維持しなくなり、V1署名アルゴリズムは新しいバケットで使用できなくなります。 ビジネスへの影響を防ぐため、できるだけ早い機会にV1シグネチャをV4シグネチャにアップグレードします。

次のサンプルコードは、V1署名アルゴリズムを使用してOSSエンドポイントを使用してOSS SDK for Pythonを初期化する方法の例を示しています。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket')                    

一般的なシナリオの構成例

このセクションでは、一般的なシナリオの設定例を示します。 サンプルコードでは、V4署名アルゴリズムとRAMユーザーのAccessKeyペアを使用して、デフォルトでOSS SDK for Pythonを初期化します。

内部エンドポイントを使用したOSS SDK for Pythonの初期化

アプリケーションがECSインスタンスにデプロイされており、ECSインスタンスと同じリージョンのバケット内のOSSデータに頻繁にアクセスする必要がある場合は、内部エンドポイントを使用してネットワークの遅延と帯域幅のコストを大幅に削減します。

次のサンプルコードは、内部エンドポイントを使用してOSSClientインスタンスを構成する方法の例を示しています。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region) 

カスタムドメイン名を使用したOSS SDK for Pythonの初期化

使用量が異なる複数のバケットがある場合は、各バケットに異なるサブドメインを指定して、リソースをより適切に管理および整理できます。

次のサンプルコードは、カスタムドメイン名を使用してOSSClientインスタンスを構成する方法の例を示しています。

警告

最初にカスタムドメイン名をバケットのデフォルトドメイン名にマップする必要があります。 それ以外の場合は、エラーが返されます。 カスタムドメイン名をバケットのデフォルトドメイン名にマップする方法の詳細については、「カスタムドメイン名をバケットのデフォルトドメイン名にマップする」をご参照ください。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
// Specify a custom domain name. Example: https://static.example.com. 
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou. 
region = 'cn-hangzhou'

# Specify the name of the bucket. Set is_cname to true to enable CNAME.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', is_cname=True, region=region) 

接続タイムアウト期間の設定

次のサンプルコードは、接続タイムアウト期間を設定する方法の例を示しています。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket and set the connection timeout period to 30 seconds. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', connect_timeout=30,region=region)                    

CRC-64を無効にする

デフォルトでは、オブジェクトのアップロードまたはダウンロード時にデータの整合性を確保するためにCRC-64が有効になります。

警告

CRC-64を無効にしないことを推奨します。 CRC-64を無効にすると、オブジェクトをアップロードまたはダウンロードするときにデータの整合性が影響を受ける可能性があります。

次のサンプルコードは、CRC-64を無効にする方法の例を示します。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket and set enable_crc to False to disable CRC-64. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', enable_crc=False,region=region)                   

接続プールサイズの指定

次のサンプルコードは、接続プールサイズを指定する方法の例を示しています。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the connection pool size. Default value: 10. 
session = oss2.Session(pool_size=20)

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session,region=region)

TLSバージョンの指定

TLS (Transport Layer Security) バージョンによって、セキュリティとパフォーマンスの機能が異なります。 シナリオに基づいてTLSバージョンを選択します。

説明

Python 2.18.1以降のOSS SDKでTLSバージョンを指定できます。

次のサンプルコードは、TLSバージョンを1.2に設定する方法の例を示しています。

# -*- coding: utf-8 -*-
import ssl
import oss2
from requests.adapters import HTTPAdapter
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Configure the SSL adapter. 
class SSLAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        # Set the TLS version to 1.2. 
        kwargs["ssl_version"] = ssl.PROTOCOL_TLSv1_2
        return super().init_poolmanager(*args, **kwargs)

# Create a session object and configure the adapter by using the session object. 
session = oss2.Session(adapter=SSLAdapter())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"

# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', session=session, region=region)

# Upload an object. 
bucket.put_object("example.txt", "hello")

oss2.Bucketクラスでサポートされているパラメーター

次の表に、oss2.Bucketクラスを初期化するときに設定できるパラメーターを示します。

パラメーター

説明

課金方法

is_cname

正しい

エンドポイントがカスタムドメイン名かどうかを指定します。 有効な値:

  • 正しい

  • False (デフォルト)

oss2.Bucket(auth, cname, 'examplebucket', is_cname=True, region=region)

セッション

mytestsession

新しいセッションが開始されることを指定するセッションの名前。 デフォルト値 : なし。 このパラメーターを既存のセッションの名前に設定すると、セッションが再利用されます。

oss2.Bucket(auth, endpoint, 'examplebucket', session=oss2.Session(), region=region)

connect_timeout

30

接続のタイムアウト期間。 デフォルト値: 60。 単位は秒です。

oss2.Bucket(auth、endpoint、'examplebucket' 、connect_timeout=30、region=region)

app_name

mytool

OSS SDK for Pythonを使用するアプリケーションの名前。 デフォルトでは、このパラメータは空のままです。 パラメータが空でない場合は、User-Agentフィールドに対応する値を指定します。

重要

文字列はHTTPヘッダー値として渡され、HTTP標準に準拠する必要があります。

oss2.Bucket(auth、endpoint、'examplebucket' 、app_name='mytool' 、region=region)

enable_crc

False

CRC-64を有効にするかどうかを指定します。

  • True (デフォルト)

  • False

oss2.Bucket(auth、endpoint、'examplebucket' 、enable_crc=False、region=region)

よくある質問

バケットと同じリージョンにある他のAlibaba Cloudサービスを使用してOSSにアクセスする場合、内部エンドポイントを使用してデータ転送を高速化できますか。

はい、内部エンドポイントを使用してデータ転送を高速化できます。 データ転送に関する要件がある場合は、OSSと同じリージョンにあるECSインスタンスなどの他のAlibaba Cloudサービスを使用してOSSにアクセスすることを推奨します。 詳細については、「同じリージョン内のECSインスタンスからのアクセス」をご参照ください。

RAMユーザーのAccessKey IDの表示方法を教えてください。 私は見ることができますAccessKey secret古いAccessKeyペアの?

  1. RAMユーザーのAccessKey IDを表示するには、RAMコンソールにログインします。

  2. RAMユーザーのAccessKeyシークレットは、AccessKeyペアが作成されたときにのみ表示されます。 AccessKeyペアを後で表示することはできません。 AccessKeyシークレットを忘れた場合、AccessKeyシークレットを取得できません。 RAMコンソールで特定のRAMユーザーを直接選択し、ローテーション用の新しいAccessKeyペアを作成できます。 詳細については、「AccessKeyペアの作成」をご参照ください。

エラーが報告された場合、エラーの特定のタイプを判断するにはどうすればよいですか?

OSSには、エラーの種類を特定するのに役立つエラーコードが用意されています。 たとえば、一般的な認証エラーについては、「02-AUTH」をご参照ください。