本文介绍如何使用范围下载方法,帮助您高效地获取文件中的特定部分数据。
注意事项
本文示例代码以华东1(杭州)的地域ID
cn-hangzhou
为例,默认使用外网Endpoint,如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见OSS地域和访问域名。要使用范围下载,您必须有
oss:GetObject
权限。具体操作,请参见为RAM用户授权自定义的权限策略。
方法定义
get_object(request: GetObjectRequest, **kwargs) → GetObjectResult
请求参数列表
参数名 | 类型 | 说明 |
参数名 | 类型 | 说明 |
request | *GetObjectRequest | 设置具体接口的请求参数,例如设置range_header指定下载范围,设置range_behavior指定标准行为的范围下载,具体请参见GetObjectRequest |
返回值列表
类型 | 说明 |
类型 | 说明 |
GetObjectResult | 接口返回值,当 err 为nil 时有效,具体请参见GetObjectResult |
假设现有大小为1000 Bytes的Object,则指定的正常下载范围应为0~999。如果指定范围不在有效区间,会导致Range不生效,响应返回值为200,并传送整个Object的内容。请求不合法的示例及返回说明如下:
若指定了Range: bytes=500-2000,此时范围末端取值不在有效区间,返回整个文件的内容,且HTTP Code为200。
若指定了Range: bytes=1000-2000,此时范围首端取值不在有效区间,返回整个文件的内容,且HTTP Code为200。
您可以在请求中增加请求头x-oss-range-behavior:standard指定标准行为范围下载,改变指定范围不在有效区间时OSS的下载行为。假设现有大小为1000 Bytes的Object:
若指定了Range: bytes=500-2000,此时范围末端取值不在有效区间,返回500~999字节范围内容,且HTTP Code为206。
若指定了Range: bytes=1000-2000,此时范围首端取值不在有效区间,返回HTTP Code为416,错误码为InvalidRange。
示例代码
以下代码展示了在请求中增加请求头RangeBehavior:standard来指定标准下载行为,下载指定范围内的文件数据。
import argparse
import alibabacloud_oss_v2 as oss
# 创建命令行参数解析器
parser = argparse.ArgumentParser(description="Get object range 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('--range', help='Specify the scope of file transfer. Example value: bytes=0-9', required=True)
parser.add_argument('--range_behavior', help='Standard for downloading behavior within a specified range. Example value: standard.')
def main():
# 解析命令行参数
args = parser.parse_args()
# 从环境变量中加载凭证信息
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客户端
client = oss.Client(cfg)
# 发起获取对象请求
result = client.get_object(oss.GetObjectRequest(
bucket=args.bucket, # 指定存储空间名称
key=args.key, # 指定对象键名
range_header=args.range, # 指定范围头
range_behavior=args.range_behavior, # 指定范围内下载行为
))
# 打印响应结果中的多个属性
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' content range: {result.content_range},'
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' next append position: {result.next_append_position},'
f' expiration: {result.expiration},'
f' restore: {result.restore},'
f' process status: {result.process_status},'
f' delete marker: {result.delete_marker},'
)
# ========== 方式1:完整读取 ==========
# 使用上下文管理器确保资源释放
with result.body as body_stream:
data = body_stream.read()
print(f"文件读取完成,数据长度:{len(data)} bytes")
path = "./get-object-sample.txt"
with open(path, 'wb') as f:
f.write(data)
print(f"文件下载完成,保存至路径:{path}")
# # ========== 方式2:分块读取 ==========
# # 使用上下文管理器确保资源释放
# with result.body as body_stream:
# chunk_path = "./get-object-sample-chunks.txt"
# total_size = 0
# with open(chunk_path, 'wb') as f:
# # 使用256KB块大小(可根据需要调整block_size参数)
# for chunk in body_stream.iter_bytes(block_size=256 * 1024):
# f.write(chunk)
# total_size += len(chunk)
# print(f"已接收数据块:{len(chunk)} bytes | 累计:{total_size} bytes")
# print(f"文件下载完成,保存至路径:{chunk_path}")
# 当脚本作为主程序运行时调用main函数
if __name__ == "__main__":
main()
相关文档
关于范围下载的完整示例代码,请参见get_object_range.py。
- 本页导读 (1)
- 注意事项
- 方法定义
- 示例代码
- 相关文档