All Products
Search
Document Center

Object Storage Service:Restore an object (Python SDK V2)

Last Updated:Aug 01, 2025

In a versioning-enabled bucket, different versions of an object can have different storage classes. The RestoreObject operation restores the current version of an object by default. You can specify a version ID to restore a specific version of the object.

Precautions

  • The sample code in this topic uses the China (Hangzhou) region (cn-hangzhou) as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about the regions and endpoints that OSS supports, see OSS regions and endpoints.

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

Sample code

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

import time
import argparse
import alibabacloud_oss_v2 as oss

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

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

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

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

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command-line arguments 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

    # Use the preceding configurations to initialize the OSS client for interacting 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 for which the restored object is retained.
            # Optional: Set the restoration priority for Cold Archive or Deep Cold Archive objects. Valid values: Expedited, Standard, and Bulk. Default value: Standard.
            # tier="Expedited",
        )
    ))

    # Print information such as the status code, request ID, version ID, and restoration 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},'  # The restoration priority, if any.
          )

    # Loop to check whether the object is restored.
    while True:
        # Obtain the header 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')  # The object is restored.
            break
        else:
            # Pause for 5 seconds and then check again.
            time.sleep(5)
            print(result.restore)  # Print the current restored state.

# If this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

References