This topic describes how to configure and query object metadata by using OSS SDK for Python.
Notes
The sample code in this topic uses the region ID
cn-hangzhou
of the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.In this topic, access credentials are obtained from environment variables. For more information about how to configure the access credentials, see Configure access credentials.
To configure object metadata, you must have the
oss:PutObject
permission. To query object metadata, you must have theoss:GetObject
permission. For more information, see Attach a custom policy to a RAM user.
Configure object metadata during object uploads
Configure object metadata during object uploads
The following sample code uploads an object by using PutObject and configures object metadata headers such as the expiration time, access control list (ACL), and some user metadata. You can configure object metadata in the same way if you use other upload API operations.
import argparse
import requests
import alibabacloud_oss_v2 as oss
from alibabacloud_oss_v2.models import (
PutObjectRequest, GetObjectRequest, DeleteObjectRequest,
ListObjectsRequest, PutBucketRequest, GetBucketAclRequest
# Any other classes that you need.
)
# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command-line parameters.
# 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.
cfg.region = args.region
# If an endpoint is provided, specify the endpoint in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configuration to create an OSSClient instance.
client = oss.Client(cfg)
# Specify the string that you want to upload.
text_string = "Hello, OSS!"
data = text_string.encode('utf-8') # Encode the string by using the UTF-8 encoding.
# Execute the request to upload the object.
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
metadata={
'key1': 'value1',
'key2': 'value2'
}
))
# Display the HTTP status code, request ID, MD5 hash, ETag, CRC-64 value, and object version ID to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.content_md5},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
)
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Query object metadata
Query all metadata of an object by using the HeadObject method
The following sample code queries all metadata of an object by using the HeadObject method:
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="head object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line parameters.
args = parser.parse_args()
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration to create a configuration object (cfg) and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region attribute of the cfg object to the region in the parser.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configuration to initialize the OSSClient instance.
client = oss.Client(cfg)
# Send a request to get the headers of the object.
result = client.head_object(oss.HeadObjectRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
))
# Print the result details.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' content type: {result.content_type},'
f' etag: {result.etag},'
f' last modified: {result.last_modified},'
f' content md5: {result.content_md5},'
f' cache control: {result.cache_control},'
f' content disposition: {result.content_disposition},'
f' content encoding: {result.content_encoding},'
f' expires: {result.expires},'
f' hash crc64: {result.hash_crc64},'
f' storage class: {result.storage_class},'
f' object type: {result.object_type},'
f' version id: {result.version_id},'
f' tagging count: {result.tagging_count},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' server side encryption key id: {result.server_side_encryption_key_id},'
f' next append position: {result.next_append_position},'
f' expiration: {result.expiration},'
f' restore: {result.restore},'
f' process status: {result.process_status},'
f' request charged: {result.request_charged},'
f' allow origin: {result.allow_origin},'
f' allow methods: {result.allow_methods},'
f' allow age: {result.allow_age},'
f' allow headers: {result.allow_headers},'
f' expose headers: {result.expose_headers},'
)
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry point of the script. The control flow starts here.
Use the GetObjectMeta method to query partial metadata of an object
You can use the GetObjectMeta method to query only partial object metadata, including the returned content length (ContentLength), entity tag (ETag), last modified time (LastModified), last access time (LastAccessTime), version ID (VersionId), and CRC-64 hash (HashCRC64).
The following sample code queries partial metadata of an object by using the GetObjectMeta method:
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="get object meta sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line parameters.
args = parser.parse_args()
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration to create a configuration object (cfg) and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region attribute of the cfg object to the region in the parser.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configuration to initialize the OSSClient instance.
client = oss.Client(cfg)
# Send a request to get the metadata of the object.
result = client.get_object_meta(oss.GetObjectMetaRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
))
# Display the HTTP status code, request ID, content length, ETag, last modification time, and last access time, object version ID, and CRC64 hash to check whether the request is successful.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' etag: {result.etag},'
f' last modified: {result.last_modified},'
f' last access time: {result.last_access_time},'
f' version id: {result.version_id},'
f' hash crc64: {result.hash_crc64},'
)
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry point of the script. The control flow starts here.
Modify metadata of an existing object
Use the CopyObject method to modify object metadata
The following sample code modifies the metadata of an object by using the CopyObject method:
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="copy object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the destination object.', required=True)
# Specify the --source_key to indicate the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source object.', required=True)
# Specify the --source_bucket parameter to indicate the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
def main():
# Parse the command-line parameters.
args = parser.parse_args()
# 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.
cfg.region = args.region
# If an endpoint is provided, specify the endpoint in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configuration to create an OSSClient instance.
client = oss.Client(cfg)
# Copy the source object.
result = client.copy_object(oss.CopyObjectRequest(
bucket=args.bucket, # Specify the name of the destination bucket.
key=args.key, # Specify the key of the destination object.
source_key=args.source_key, # Specify the key of the source object.
source_bucket=args.source_bucket, # Specify the name of the source bucket.
metadata={'key1': 'value1', 'key2': 'value2'}, # Specify the metadata.
metadata_directive='REPLACE', # Specify the metadata directive.
))
# Display the details of the operation result.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' version id: {result.version_id},'
f' hash crc64: {result.hash_crc64},'
f' source version id: {result.source_version_id},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' last modified: {result.last_modified},'
f' etag: {result.etag},'
)
# 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 Copier.Copy to modify object metadata
You can use Copier.Copy to copy a source object and configure metadata for the destination object. For example, you can overwrite all existing original metadata with new metadata, remove original metadata, and update only the specified metadata headers. You can also specify whether to delete the source object after the copy operation completes.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="copier sample")
# Specify the region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the bucket parameter to indicate the name of the destination bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the endpoint parameter to indicate the OSS endpoint that is used to access OSS. This parameter is optional
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the key parameter to indicate the name of the destination object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Specify the source_key parameter to indicate the name of the source object. This parameter is required.
parser.add_argument('--source_key', help='The name of the source address for object.', required=True)
# Specify the source_bucket parameter to indicate the name of the source bucket. This parameter is required.
parser.add_argument('--source_bucket', help='The name of the source address for bucket.', required=True)
def main():
# Parse the command-line parameters.
args = parser.parse_args()
# Obtain access credentials from environment variables.
# Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration of the SDK.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider # Specify the credential provider.
cfg.region = args.region # Specify the region in which the bucket is located.
if args.endpoint is not None:
cfg.endpoint = args.endpoint # If an endpoint is provided, specify the endpoint in the configuration object.
# Create an OSSClient instance.
client = oss.Client(cfg)
# Create a copier instance.
copier = client.copier()
# Copy the source object.
result = copier.copy(
oss.CopyObjectRequest(
bucket=args.bucket, # The name of the destination bucket.
key=args.key, # The name of the destination object.
source_bucket=args.source_bucket, # The name of the source bucket.
source_key=args.source_key, # The key of the source object.
metadata={'key1': 'value1', 'key2': 'value2'}, # The metadata of the destination object.
metadata_directive="REPLACE", # Specify the metadata directive.
)
)
# Display the object copy result.
# Return a dictionary of attributes of the result object by using vars() and display the dictionary.
print(vars(result))
if __name__ == "__main__":
main()