All Products
Search
Document Center

Object Storage Service:Restore objects

Last Updated:Mar 08, 2025

In a bucket with versioning enabled, storage classes for different object versions may vary. The RestoreObject interface, by default, restores the current version of an object. To restore a specific version, you must provide the versionId.

Notes

  • The sample code in this topic uses the China (Hangzhou) region ID cn-hangzhou as an example and defaults to the Internet endpoint. For OSS access through other Alibaba Cloud products within the same region, use the internal endpoint. For details on OSS region and endpoint mapping, see OSS regions and endpoints.

  • To restore an object, you must have the oss:RestoreObject permission. For more information, see Grant custom policy to RAM users.

Sample code

You can use the following code to restore objects from the Archive, Cold Archive, or Deep Cold Archive storage classes:

import time
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the script's purpose: restore object sample
parser = argparse.ArgumentParser(description="restore object sample")

# Add command line argument --region, indicating the region in which the bucket is located, required parameter
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add command line argument --bucket, indicating the name of the bucket, required parameter
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add command line argument --endpoint, indicating the domain names that other services can use to access OSS, optional parameter
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add command line argument --key, indicating the name of the object, required parameter
parser.add_argument('--key', help='The name of the object.', required=True)
# Add command line argument --version_id, indicating the version ID of the object, required parameter
parser.add_argument('--version_id', help='The version ID of the object.', required=True)

def main():
    # Parse the parameters provided by the command line to obtain the values entered by the user
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for authentication
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the SDK's default configuration and set the credentials provider
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command line parameters provided by the user
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the above configuration to prepare for interaction with OSS
    client = oss.Client(cfg)

    # Send a request to restore the object
    result = client.restore_object(oss.RestoreObjectRequest(
        bucket=args.bucket,           # Specify the bucket name
        key=args.key,                 # Specify the object name
        version_id=args.version_id,   # Specify the version ID of the object
        restore_request=oss.RestoreRequest(
            days=1,                    # Specify the number of days to retain the object after restoration
            # Optional: Set the restore priority for Cold Archive or Deep Cold Archive. Options are: Expedited, Standard, Bulk. Default is Standard
            # tier="Expedited",
        )
    ))

    # Print the status code, request ID, version ID, and restore priority of the operation result to confirm the request status
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' restore priority: {result.restore_priority},'  # Restore priority (if any)
          )

    # Loop to check whether the object has been restored
    while True:
        # Obtain the header information of the object
        result = client.head_object(oss.HeadObjectRequest(
            bucket=args.bucket,
            key=args.key,
            version_id=args.version_id,
        ))

        # Check the restored state
        if result.restore and result.restore != 'ongoing-request="true"':
            print('restore is success')  # Restore successful
            break
        else:
            # Pause for 5 seconds and then check again
            time.sleep(5)
            print(result.restore)  # Print the current restored state

# When this script is executed directly, call the main function to start processing logic
if __name__ == "__main__":
    main()  # Entry point of the script, control program flow starts here

References