A bucket is a container for storing objects in Object Storage Service (OSS). Use the get_bucket_location() method to retrieve the region where a bucket is located.
Prerequisites
Before you begin, make sure that you have:
Configured the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables with your access credentialsGranted the
oss:GetBucketLocationpermission to the account. For details, see Attach a custom policy to a RAM user
To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead of the public endpoint used in the sample code below. For the full list of regions and endpoints, see Regions and endpoints.
Get the bucket region
The following example uses ProviderAuthV4 with environment variable credentials and calls get_bucket_location() to get the region. The region parameter is required for V4 signatures.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Load access credentials from environment variables:
# OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Endpoint of the region where the bucket is located.
# Example: China (Hangzhou) -> https://oss-cn-hangzhou.aliyuncs.com
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Region ID -- required for V4 signatures.
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Get the bucket region.
result = bucket.get_bucket_location()
print('location: ' + result.location)What's next
For the complete sample code, see GitHub
For the underlying REST API, see GetBucketLocation
To initialize an OSSClient instance using a custom domain or Security Token Service (STS), see Initialization