Python获取文件元数据

更新时间:2025-03-07 06:25:45

本文介绍如何在受版本控制的存储空间(Bucket)中获取文件(Object)元数据。

注意事项

  • 本文示例代码以华东1(杭州)的地域IDcn-hangzhou为例,默认使用外网Endpoint,如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的RegionEndpoint的对应关系,请参见OSS地域和访问域名

  • 要获取文件元数据,您必须有oss:GetObject权限。具体操作,请参见RAM用户授权自定义的权限策略

示例代码

使用HeadObject方法获取对象的所有元数据

您可以通过以下代码使用HeadObject方法获取指定对象版本的所有元数据。

import argparse
import alibabacloud_oss_v2 as oss

# 创建命令行参数解析器,并描述脚本用途:获取对象头部信息示例
parser = argparse.ArgumentParser(description="head object sample")

# 添加命令行参数 --region,表示存储空间所在的区域,必需参数
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令行参数 --bucket,表示存储空间的名称,必需参数
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令行参数 --endpoint,表示其他服务可用来访问OSS的域名,非必需参数
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令行参数 --key,表示对象的名称,必需参数
parser.add_argument('--key', help='The name of the object.', required=True)
# 添加命令行参数 --version_id,表示对象的版本ID,必需参数
parser.add_argument('--version_id', help='The version ID of the object.', required=True)

def main():
    # 解析命令行提供的参数,获取用户输入的值
    args = parser.parse_args()

    # 从环境变量中加载访问OSS所需的认证信息,用于身份验证
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK的默认配置创建配置对象,并设置认证提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 设置配置对象的区域属性,根据用户提供的命令行参数
    cfg.region = args.region

    # 如果提供了自定义endpoint,则更新配置对象中的endpoint属性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS客户端,准备与OSS交互
    client = oss.Client(cfg)

    # 发送请求以获取对象的头部信息
    result = client.head_object(oss.HeadObjectRequest(
        bucket=args.bucket,           # 指定存储空间名称
        key=args.key,                 # 指定对象名称
        version_id=args.version_id,   # 指定对象的版本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},'
          )

# 当此脚本被直接执行时,调用main函数开始处理逻辑
if __name__ == "__main__":
    main()  # 脚本入口点,控制程序流程从这里开始

使用GetObjectMeta方法获取对象的部分元数据

说明

使用GetObjectMeta方法仅可以获取部分的对象元数据,包括:返回内容的长度(ContentLength)、实体标签(ETag)、返回的对象最后一次被修改的时间(LastModified)、对象最后一次被访问的时间(LastAccessTime)、对象的版本ID(VersionId)、对象的 64 位 CRC 值(HashCRC64)。

您可以通过以下代码使用GetObjectMeta方法获取指定对象版本的部分元数据。

import argparse
import alibabacloud_oss_v2 as oss

# 创建命令行参数解析器,并描述脚本用途:获取对象元数据示例
parser = argparse.ArgumentParser(description="get object meta sample")

# 添加命令行参数 --region,表示存储空间所在的区域,必需参数
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令行参数 --bucket,表示存储空间的名称,必需参数
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令行参数 --endpoint,表示其他服务可用来访问OSS的域名,非必需参数
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令行参数 --key,表示对象的名称,必需参数
parser.add_argument('--key', help='The name of the object.', required=True)
# 添加命令行参数 --version_id,表示对象的版本ID,必需参数
parser.add_argument('--version_id', help='The version id of the object.', required=True)

def main():
    # 解析命令行提供的参数,获取用户输入的值
    args = parser.parse_args()

    # 从环境变量中加载访问OSS所需的认证信息,用于身份验证
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # 使用SDK的默认配置创建配置对象,并设置认证提供者
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # 设置配置对象的区域属性,根据用户提供的命令行参数
    cfg.region = args.region

    # 如果提供了自定义endpoint,则更新配置对象中的endpoint属性
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # 使用上述配置初始化OSS客户端,准备与OSS交互
    client = oss.Client(cfg)

    # 发送请求以获取对象的元数据
    result = client.get_object_meta(oss.GetObjectMetaRequest(
        bucket=args.bucket,           # 指定存储空间名称
        key=args.key,                 # 指定对象名称
        version_id=args.version_id,   # 指定对象的版本ID
    ))

    # 打印操作结果的状态码、请求ID、内容长度、ETag、最后修改时间、最后访问时间、版本ID以及哈希CRC64等信息,以便确认请求状态
    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},'
          )

# 当此脚本被直接执行时,调用main函数开始处理逻辑
if __name__ == "__main__":
    main()  # 脚本入口点,控制程序流程从这里开始
  • 本页导读 (1)
  • 注意事项
  • 示例代码
  • 使用HeadObject方法获取对象的所有元数据
  • 使用GetObjectMeta方法获取对象的部分元数据