When you use OSS SDK for Python 2.0 to initiate a request, you must initialize a Client instance for accessing Object Storage Service (OSS) and modify the default configuration items as needed.
Notes
Before you initialize a Client instance, you must configure access credentials. In this topic, access credentials are obtained from environment variables. For more information, see Configure access credentials.
For a list of regions and endpoints, see Regions and endpoints.
Prerequisites
Before you configure a client using the following code samples, you must configure environment variables to store the AccessKey pair of a RAM user.
Configure environment variables
Configure environment variables for the AccessKey pair.
Linux
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
Run the following command to apply the changes:
source ~/.bashrc
Run the following commands to check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to view the default shell type:
echo $SHELL
Configure environment variables based on the default shell type.
Zsh
Run the following commands to add the configurations of the environment variables to the
~/.zshrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes:
source ~/.zshrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add the configurations of the environment variables to the
~/.bash_profile
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
Run the following command to apply the changes:
source ~/.bash_profile
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in 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)
Run the following commands to check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
After configuring the environment variables as described above, please restart or refresh your compilation and runtime environment, namely IDEs, command-line interfaces, other desktop applications, and background services, to ensure that the latest system environment variables are successfully loaded.
Default configuration example
OSS SDK for Python 2.0 uses the V4 signature algorithm to initialize a Client instance by default. You must specify an Alibaba Cloud region ID as the identifier of the region to which the request is sent. In this example, the region ID of the China (Hangzhou) region (cn-hangzhou) is used. For information about the IDs of other regions, see Regions and endpoints.
OSS SDK for Python 2.0 uses the endpoint parameter to specify the endpoint for a request. If the endpoint parameter is not specified, OSS SDK for Python 2.0 automatically constructs and uses a public endpoint for the specified region. For example, if the region is cn-hangzhou, https://oss-cn-hangzhou.aliyuncs.com is used.
OSS SDK for Python 2.0 uses the HTTPS protocol by default when constructing an endpoint. If you want to use the HTTP protocol, declare http. Example: http://oss-cn-hangzhou.aliyuncs.com.
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify only the region.
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# # Method 2: Specify the endpoint and region.
# # Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
# cfg.region = 'cn-hangzhou'
# # Specify the public 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.
# # To use the HTTP protocol, set the endpoint to http://oss-cn-hangzhou.aliyuncs.com.
# cfg.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Configuration examples in common scenarios
Use an internal endpoint to configure a Client instance
If your applications are deployed on an Elastic Compute Service (ECS) instance and you need to frequently access data in an OSS bucket in the same region as the ECS instance, use an internal endpoint to significantly reduce network latency and bandwidth costs.
The following sample code uses an internal endpoint to configure a Client instance:
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify the region and set use_internal_endpoint to true.
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg = oss.config.load_default()
cfg.region = 'cn-hangzhou'
cfg.use_internal_endpoint = True
# # Method 2: Specify the internal endpoint and region.
# # Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
# cfg.region = 'cn-hangzhou'
# # Specify the internal 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.
# cfg.endpoint = 'https://oss-cn-hangzhou-internal.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Use a custom domain name to configure a Client instance
If you have multiple buckets for different use cases, you can specify different subdomains for each bucket to better manage and organize resources.
The following sample code uses a custom domain name to configure a Client instance:
You must first map the custom domain name to the default domain name of the bucket. Otherwise, an error is reported. For more information about how to map a custom domain name, see Map a custom domain name to the default domain name of a bucket.
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# Specify a custom domain name. Example: www.example-***.com.
cfg.endpoint = 'https://www.example-***.com'
# To enable CNAME, set this parameter to True. Otherwise, you cannot use a custom domain name.
cfg.use_cname = True
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Use an acceleration endpoint to configure a Client instance
The following sample code uses an acceleration endpoint to configure a Client instance:
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify the region and set use_accelerate_endpoint to true.
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
cfg.use_accelerate_endpoint = True
# # Method 2: Specify the acceleration endpoint and region.
# # Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
# cfg.region = 'cn-hangzhou'
# # Specify the acceleration 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-accelerate.aliyuncs.com.
# cfg.endpoint = 'https://oss-accelerate.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Use a private domain to configure a Client instance
The following sample code uses a private domain to configure a Client instance:
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# Specify the private domain. Example: https://service.corp.example.com.
cfg.endpoint = 'https://service.corp.example.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Configuration example for Alibaba Finance Cloud
The following sample code uses an endpoint of Alibaba Finance Cloud to configure a Client instance:
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region and endpoint.
# Specify the region in which the bucket is located. For example, if the bucket is located in the China East 1 Finance region, set the region to cn-hangzhou-finance.
cfg.region = 'cn-hangzhou-finance'
# Specify the internal endpoint of the region in which the bucket is located. For example, if the bucket is located in the China East 1 Finance region, set the endpoint to https://oss-cn-hzjbp-a-internal.aliyuncs.com.
# To use the HTTP protocol, set the endpoint to http://oss-cn-hzjbp-a-internal.aliyuncs.com.
cfg.endpoint = 'https://oss-cn-hzjbp-a-internal.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Configuration example for Alibaba Gov Cloud
The following sample code uses an endpoint of Alibaba Gov Cloud to configure a Client instance:
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region and endpoint.
# Specify the region in which the bucket is located. For example, if the bucket is located in the China North 2 Ali Gov 1 region, set the region to cn-north-2-gov-1.
cfg.region = 'cn-north-2-gov-1'
# Specify the internal endpoint of the region in which the bucket is located. For example, if the bucket is located in the China North 2 Ali Gov 1 region, set the endpoint to https://oss-cn-north-2-gov-1-internal.aliyuncs.com.
# To use the HTTP protocol, set the endpoint to http://oss-cn-north-2-gov-1-internal.aliyuncs.com.
cfg.endpoint = 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
More configuration examples
Configure the timeout period
The following sample code configures a connection timeout period for a Client instance:
import alibabacloud_oss_v2 as oss
from typing import Dict, Any
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration.
cfg = oss.config.load_default()
# Specify the timeout period for establishing a connection. Default value: 10. Unit: seconds.
cfg.connect_timeout = 30
# Specify the timeout period for the application to read and write data. Default value: 20. Unit: seconds.
cfg.readwrite_timeout = 30
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Configure retry policies
OSS SDK for Python provides retry policies to handle request failures caused by network fluctuations or temporary service exceptions. Refer to the following sample code to add optional parameters to configure the number of retries when initializing a Client instance.
Default retry policy
When no retry policy is configured, the SDK uses StandardRetryer() as the default retry implementation for the client, with the following default settings:
max_attempts: Sets the maximum number of attempts. Default value: 3.
max_backoff: Sets the maximum backoff time (in seconds). Default value: 20.
base_delay: Sets the base delay time (in seconds). Default value: 0.2.
backoff_delayer: Sets the backoff algorithm. The default is the FullJitter backoff algorithm, with the formula [0.0, 1.0) × min(2 ^ attempts × baseDealy, maxBackoff).
When a retryable error occurs, the system uses the provided retry settings to delay and retry the request. The overall delay of the request increases with the number of retries. If the default configuration does not meet your requirements, you can configure retry parameters or modify the retry implementation.
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration.
cfg = oss.config.load_default()
# Set the maximum number of retries. Default value: 3.
cfg.retryer = oss.retry.StandardRetryer(max_attempts=5)
# Set the backoff delay time, adjust the base delay time base_delay to 500 milliseconds, and the maximum backoff time max_backoff to 25 seconds.
# cfg.retryer = oss.retry.StandardRetryer(max_backoff=25, base_delay=0.5)
# Set the backoff algorithm, use a fixed time backoff algorithm with a 2-second delay each time.
# cfg.retryer = oss.retry.StandardRetryer(backoff_delayer=oss.retry.FixedDelayBackoff(2))
# To disable all retry attempts, you can use the retry.NopRetryer implementation.
# cfg.retryer = oss.retry.NopRetryer()
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Use an HTTP client to configure a Client instance
If common parameters cannot meet the requirements of your business scenario, you can use cfg.http_client to replace the default HTTP client.
import alibabacloud_oss_v2 as oss
from typing import Dict, Any
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration.
cfg = oss.config.load_default()
# Specify the parameters of the HTTP client.
kwargs: Dict[str, Any] = {}
# Set the session.
# kwargs["session"] = requests.Session()
# Set the adapter.
# kwargs["adapter"] = HTTPAdapter()
# Specify whether to skip certificate verification. By default, certificate verification is not skipped.
# kwargs["insecure_skip_verify"] = False
# Specify whether to enable HTTP redirection. By default, HTTP redirection is disabled.
# kwargs["enabled_redirect"] = False
# Specify a proxy server.
# kwargs["proxy_host"] = config.proxy_host
# Set the block size.
# kwargs["block_size"] = 16 * 1024
# The timeout period to establish a connection. Default value: 10 seconds.
kwargs["connect_timeout"] = 30
# The timeout period for the application to read and write data. Default value: 20. Unit: seconds.
kwargs["readwrite_timeout"] = 30
# The maximum number of connections. Default value: 20.
kwargs["max_connections"] = 1024
# Create an HTTP client and specify the HTTP client parameters.
cfg.http_client = oss.transport.RequestsHttpClient(**kwargs)
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
cfg.region = 'cn-hangzhou'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
OSSClient configuration parameters
Parameter | Description | Example |
region | (Required) The region to which the request is sent. | oss.config.Config(region="cn-hangzhou") |
credentials_provider | (Required) The access credentials. | oss.config.Config(credentials_provider=provider) |
endpoint | The endpoint. | oss.config.Config(endpoint="oss-cn-hangzhou.aliyuncs.com") |
http_client | The HTTP client. | oss.config.Config(http_client=customClient) |
retry_max_attempts | The maximum number of HTTP retries. Default value: 3. | oss.config.Config(retry_max_attempts=5) |
retryer | The retry configuration for HTTP requests. | oss.config.Config(retryer=customRetryer) |
connect_timeout | The timeout period for establishing a connection. Unit: seconds. Default value: 10. | oss.config.Config(connect_timeout=20) |
readwrite_timeout | The timeout period for the application to read and write data. Default value: 20. Unit: seconds. | oss.config.Config(readwrite_timeout=30) |
insecure_skip_verify | Specifies whether to skip SSL certificate verification. By default, the SSL certificates are verified. | oss.config.Config(insecure_skip_verify=True) |
enabled_redirect | Specifies whether to enable HTTP redirection. By default, HTTP redirection is disabled. | oss.config.Config(enabled_redirect=True) |
proxy_host | Specifies a proxy server. | oss.config.Config(proxy_host="http://user:passswd@proxy.example-***.com") |
signature_version | The signature version. Default value: v4 | oss.config.Config(signature_version="v1") |
disable_ssl | Specifies that HTTPS is not used for requests. HTTPS is used by default. | oss.config.Config(disable_ssl=True) |
use_path_style | The path request style, which is also known as the root domain name request style. By default, the default domain name of the bucket is used. | oss.config.Config(use_path_style=True) |
use_cname | Specifies whether to use a custom domain name to access OSS. By default, a custom domain name is not used. | oss.config.Config(use_cname=True) |
use_dualstack_endpoint | Specifies whether to use a dual-stack endpoint to access OSS. By default, a dual-stack endpoint is not used. | oss.config.Config(use_dualstack_endpoint=True) |
use_accelerate_endpoint | Specifies whether to use an acceleration endpoint to access OSS. By default, an acceleration endpoint is not used. | oss.config.Config(use_accelerate_endpoint=True) |
use_internal_endpoint | Specifies whether to use an internal endpoint to access OSS. By default, an internal endpoint is not used. | oss.config.Config(use_internal_endpoint=True) |
disable_upload_crc64_check | Specifies that CRC-64 is disabled during object upload. By default, CRC-64 is enabled. | oss.config.Config(disable_upload_crc64_check=True) |
disable_download_crc64_check | Specifies that CRC-64 is disabled during object download. By default, CRC-64 is enabled. | oss.config.Config(disable_download_crc64_check=True) |
additional_headers | The additional headers used for signature. This parameter is valid only if the V4 signature algorithm is used. | oss.config.Config(additional_headers=["content-length"]) |
user_agent | The additional User-Agent request header. | oss.config.Config(user_agent="user identifier") |
FAQ
How can I accelerate data transfer when data in an OSS bucket is accessed by other Alibaba Cloud services in the same region as the OSS bucket?
How do I view the AccessKey pair of a RAM user?
If an error is reported, how do I determine the specific type of the error?
References
For more information about how to configure a Client instance, see Developer Guide.