このトピックでは、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
CLIで次のコマンドを実行して、環境変数の設定を
~/.bashrc
ファイルに追加します。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
次のコマンドを実行して変更を適用します。
source ~/.bashrc
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
ターミナルで次のコマンドを実行して、デフォルトのシェルタイプを表示します。
echo $SHELL
デフォルトのシェルタイプに基づいて環境変数を設定します。
Zsh
次のコマンドを実行して、環境変数の設定を
~/.zshrc
ファイルに追加します。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
次のコマンドを実行して変更を適用します。
source ~/.zshrc
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
バッシュ
次のコマンドを実行して、環境変数の設定を
~/.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
次のコマンドを実行して変更を適用します。
source ~/.bash_profile
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
CMDで次のコマンドを実行します。
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
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)
次のコマンドを実行して、環境変数が有効かどうかを確認します。
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
デフォルトの例
このセクションでは、V4署名アルゴリズムとV1署名アルゴリズムを使用してOSS SDK for Pythonを初期化する方法の例を示します。
次のサンプルコードでは、バケットのパブリックエンドポイントとRAMユーザーのAccessKeyペアを使用しています。
(非推奨) V1署名アルゴリズムの使用
一般的なシナリオの構成例
このセクションでは、一般的なシナリオの設定例を示します。 サンプルコードでは、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 | 正しい | エンドポイントがカスタムドメイン名かどうかを指定します。 有効な値:
| 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を有効にするかどうかを指定します。
| oss2.Bucket(auth、endpoint、'examplebucket' 、enable_crc=False、region=region) |