本文介紹如何使用範圍下載方法,協助您高效地擷取檔案中的特定部分資料。
注意事項
本文範例程式碼以華東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。