Obtain object metadata (Python SDK V2)

更新时间:
复制 MD 格式

Retrieve metadata for a specific version of an object in a versioning-enabled bucket using HeadObject or GetObjectMeta.

Prerequisites

Before you begin, ensure that you have:

Choose a method

MethodReturnsUse when
HeadObjectFull system metadata: content type, ETag, storage class, server-side encryption, CORS headers, and moreYou need complete metadata for processing, auditing, or conditional logic
GetObjectMetaLightweight subset: content length, ETag, last modified time, last access time, version ID, and hash CRC64You only need to check object size, existence, or modification time
GetObjectMeta sends a lighter-weight request. Use it when you don't need the full metadata set.

Get full metadata with HeadObject

HeadObject returns all system metadata for the specified object version without downloading the object body.

result = client.head_object(oss.HeadObjectRequest(
    bucket="<your-bucket>",
    key="<your-object-key>",
    version_id="<version-id>",
))

The response includes the following fields:

FieldDescription
content_lengthObject size in bytes
content_typeMIME type of the object
etagETag for data integrity verification
last_modifiedTimestamp of the last modification
content_md5Base64-encoded MD5 digest
storage_classStorage class (Standard, IA, Archive, etc.)
object_typeObject type (Normal, Multipart, or Appendable)
version_idVersion ID of this object version
server_side_encryptionServer-side encryption algorithm, if enabled
server_side_data_encryptionData encryption algorithm used with SSE-KMS, if applicable
server_side_encryption_key_idKey ID used for SSE-KMS encryption, if applicable
hash_crc64CRC-64 checksum for data integrity
tagging_countNumber of tags on the object
expirationLifecycle expiration rule that applies to this object, if any
restoreRestore status; only present for Archive-class objects
next_append_positionNext write position; only present for Appendable objects
process_statusImage processing status
request_chargedIndicates requester-pays billing if enabled
cache_controlHTTP Cache-Control header value
content_dispositionHTTP Content-Disposition header value
content_encodingHTTP Content-Encoding header value
expiresHTTP Expires header value
allow_originCORS allowed origins
allow_methodsCORS allowed HTTP methods
allow_ageCORS preflight cache duration
allow_headersCORS allowed request headers
expose_headersCORS headers exposed to browsers

Full example

The following script accepts command-line arguments and prints all metadata fields returned by HeadObject.

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="head object sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--version_id', help='The version ID of the object.', required=True)

def main():
    args = parser.parse_args()

    # Load credentials from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.head_object(oss.HeadObjectRequest(
        bucket=args.bucket,
        key=args.key,
        version_id=args.version_id,
    ))

    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},'
          )

if __name__ == "__main__":
    main()

Run the script by passing the required arguments:

python head_object.py \
  --region cn-hangzhou \
  --bucket <your-bucket> \
  --key <your-object-key> \
  --version_id <version-id>
The example uses cn-hangzhou as the region and a public endpoint by default. To access OSS from another Alibaba Cloud service in the same region, pass an internal endpoint via --endpoint. For a full list of regions and endpoints, see OSS regions and endpoints.

Get lightweight metadata with GetObjectMeta

GetObjectMeta returns a subset of system metadata without the overhead of a full HeadObject call. It returns only: content length, ETag, last modified time, last access time, version ID, and hash CRC64.

result = client.get_object_meta(oss.GetObjectMetaRequest(
    bucket="<your-bucket>",
    key="<your-object-key>",
    version_id="<version-id>",
))

Full example

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="get object meta sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--version_id', help='The version id of the object.', required=True)

def main():
    args = parser.parse_args()

    # Load credentials from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.get_object_meta(oss.GetObjectMetaRequest(
        bucket=args.bucket,
        key=args.key,
        version_id=args.version_id,
    ))

    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},'
          )

if __name__ == "__main__":
    main()

Run the script:

python get_object_meta.py \
  --region cn-hangzhou \
  --bucket <your-bucket> \
  --key <your-object-key> \
  --version_id <version-id>

What's next