El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Object Storage Service/ SDK Reference/ Python/ Bucket-Related APIs (SDK for Python)/ Configuring Lifecycle Rules for a Bucket (SDK for Python)

Configuring Lifecycle Rules for a Bucket (SDK for Python)

Updated on 2024-11-26 GMT+08:00

Function

You can configure lifecycle rules to periodically delete objects or transition objects between storage classes. For more information, see Lifecycle Management.

This API configures lifecycle rules for a bucket.

NOTE:
  • Expired objects will be permanently deleted and cannot be recovered.
  • Multi-AZ redundancy is not available for Archive storage. For this reason, buckets or objects with multi-AZ redundancy cannot be transitioned to the Archive storage class based on a lifecycle rule.
  • The minimum storage duration is 30 days for Infrequent Access storage, and 90 days for Archive storage. After an object is transitioned to the Archive storage class, if it stays in this storage class for less than 90 days, you still need to pay for a full 90 days.

Restrictions

  • There is no limit on the number of lifecycle rules in a bucket, but the total size of XML descriptions about all lifecycle rules in a bucket cannot exceed 20 KB.
  • A maximum of 20 lifecycle rules can be configured for a parallel file system.
  • To configure a lifecycle rule for a bucket, you must be the bucket owner or have the required permission (obs:bucket:PutLifecycleConfiguration in IAM or PutLifecycleConfiguration in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Creating a Custom Bucket Policy.
  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.

Method

ObsClient.setBucketLifecycle(bucketName, lifecycle, extensionHeaders)

Request Parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

str

Yes

Explanation:

Bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Default value:

None

lifecycle

Lifecycle

Yes

Explanation:

List of lifecycle rules. For details, see Table 1.

Default value:

None

extensionHeaders

dict

No

Explanation:

Extension headers.

Value range:

See User-defined Header (SDK for Python).

Default value:

None

Table 1 Lifecycle

Parameter

Type

Mandatory (Yes/No)

Description

rule

list of Rule

Yes

Explanation:

List of lifecycle rules. For details, see Table 2.

Default value:

None

Table 2 Rule

Parameter

Type

Mandatory (Yes/No)

Description

id

str

No

Explanation:

Lifecycle rule ID

Value range:

The value must contain 1 to 255 characters.

Default value:

None

prefix

str

Yes

Explanation:

Object name prefix. It identifies the objects the rule applies to. You can leave this parameter blank to apply the rule to all objects in the bucket.

Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you set Prefix to ExampleObject.jpg, the rule applies to object ExampleObject.jpg only. If you set Prefix to logs/, the rule applies to the three objects with name starting with logs/. If you leave Prefix blank, the rule applies to all objects in the bucket.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

status

str

Yes

Explanation:

Whether the rule is enabled

Value range:

  • Enabled
  • Disabled

Default value:

None

transition

Transition

or

list of Transition

No

Explanation:

Policies for storage class transition, including transition time and the storage class after transition. For details, see Table 3.

Restrictions:

This parameter applies only to the current object version.

Default value:

None

expiration

Expiration

No

Explanation:

Object expiration time. For details, see Table 4.

Restrictions:

This parameter applies only to the current object version.

Default value:

None

noncurrentVersionTransition

NoncurrentVersionTransition

or

list of NoncurrentVersionTransition

No

Explanation:

Policies for storage class transition, including transition time and the storage class after transition. For details, see Table 7.

Restrictions:

  • This parameter applies only to noncurrent object versions.
  • Versioning is enabled (or suspended after being enabled) for the bucket.
  • This parameter is not available for parallel file systems.

Default value:

None

noncurrentVersionExpiration

NoncurrentVersionExpiration

No

Explanation:

Expiration time of noncurrent object versions. For details, see Table 8.

Restrictions:

  • This parameter applies only to noncurrent object versions.
  • Versioning is enabled (or suspended after being enabled) for the bucket.
CAUTION:

This parameter is not available for parallel file systems.

Default value:

None

Table 3 Transition

Parameter

Type

Mandatory (Yes/No)

Description

storageClass

str

Yes if used as a request parameter

Explanation:

Storage class of the object after transition

Restrictions:

  • The Standard storage class is not supported.
  • Restrictions on storage class transitions:
    • Only transitions from the Standard storage class to the Infrequent Access storage class are supported. To transition objects from Infrequent Access to Standard, you must manually do it.
    • Only transitions from the Standard or Infrequent Access storage class to the Archive storage class are supported. To transition objects from Archive to Standard or Infrequent Access, you must restore the objects first and then manually transition their storage class.
    • Multi-AZ redundancy is not available for Archive storage. For this reason, buckets or objects with multi-AZ redundancy cannot be transitioned to the Archive storage class based on a lifecycle rule.

Value range:

See Table 5.

Default value:

None

date

str

or

DateTime

Yes if the parameter is used as a request parameter and days is absent

Explanation:

OBS executes the lifecycle rule for objects that were modified before the specified date.

Restrictions:

The value must conform with the ISO8601 standards and indicate UTC 00:00. For example, 2018-01-01T00:00:00.000Z indicates only objects that were last modified before the specified time are transitioned to the specified storage class.

For example, DateTime(year=2023, month=9, day=12)

Default value:

None

days

int

Yes if the parameter is used as a request parameter and date is absent

Explanation:

Number of days (since the last update was made to the object) after which the lifecycle rule takes effect

Restrictions:

This parameter applies only to the current object version.

Value range:

An integer greater than or equal to 0, in days

Default value:

None

Table 4 Expiration

Parameter

Type

Mandatory (Yes/No)

Description

date

str

or

DateTime

Yes if the parameter is used as a request parameter and days is absent

Explanation:

OBS executes the lifecycle rule for objects that were modified before the specified date.

Restrictions:

The value must conform with the ISO8601 standards and indicate UTC 00:00. For example, 2018-01-01T00:00:00.000Z indicates only objects that were last modified before the specified time are deleted.

For example, DateTime(year=2023, month=9, day=12)

Default value:

None

days

int

Yes if the parameter is used as a request parameter and date is absent

Explanation:

Number of days (since the last update was made to the object) after which the lifecycle rule takes effect

Restrictions:

This parameter applies only to the current object version.

Value range:

An integer greater than or equal to 0, in days

Default value:

None

Table 5 StorageClass

Parameter

Type

Description

STANDARD

Standard storage class

Explanation:

Features low access latency and high throughput and is used for storing massive, frequently accessed (multiple times a month) or small objects (< 1 MB) requiring quick response.

WARM

Infrequent Access storage class

Explanation:

Used for storing data that is semi-frequently accessed (fewer than 12 times a year) but is instantly available when needed.

COLD

Archive storage class

Explanation:

Used for storing rarely accessed (once a year) data.

Table 6 DateTime

Parameter

Type

Description

year

int

Explanation:

Year in UTC

Default value:

None

month

int

Explanation:

Month in UTC

Default value:

None

day

int

Explanation:

Day in UTC

Default value:

None

hour

int

Explanation:

Hour in UTC

Restrictions:

The value is in 24-hour format.

Default value:

0

min

int

Explanation:

Minute in UTC

Default value:

0

sec

int

Explanation:

Second in UTC

Default value:

0

Table 7 NoncurrentVersionTransition

Parameter

Type

Mandatory (Yes/No)

Description

storageClass

str

Yes if used as a request parameter

Explanation:

Storage class of noncurrent object versions after transition

Restrictions:

  • The Standard storage class is not supported.
  • Restrictions on storage class transitions:
    • Only transitions from the Standard storage class to the Infrequent Access storage class are supported. To transition objects from Infrequent Access to Standard, you must manually do it.
    • Only transitions from the Standard or Infrequent Access storage class to the Archive storage class are supported. To transition objects from Archive to Standard or Infrequent Access, you must restore the objects first and then manually transition their storage class.
    • Multi-AZ redundancy is not available for Archive storage. For this reason, buckets or objects with multi-AZ redundancy cannot be transitioned to the Archive storage class based on a lifecycle rule.

Value range:

See Table 5.

Default value:

None

noncurrentDays

int

Yes if used as a request parameter

Explanation:

Number of days an object is noncurrent before the specified rule takes effect

Restrictions:

This parameter applies only to noncurrent object versions.

Value range:

An integer greater than or equal to 0, in days

Default value:

None

Table 8 NoncurrentVersionExpiration

Parameter

Type

Mandatory (Yes/No)

Description

noncurrentDays

int

Yes if used as a request parameter

Explanation:

Number of days an object is noncurrent before the specified rule takes effect

Restrictions:

This parameter applies only to noncurrent object versions.

Value range:

An integer greater than or equal to 0, in days

Default value:

None

Responses

Type

Description

GetResult

Explanation:

SDK common results

Table 9 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits ranging from 2xx (indicating successes) to 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description.

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server.

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, the value of body is null. The value varies with the API being called. For details, see Bucket-Related APIs (SDK for Python) and Object-Related APIs (SDK for Python).

Default value:

None

Code Examples

This example configures a lifecycle rule for bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from obs import ObsClient
from obs import Expiration, NoncurrentVersionExpiration
from obs import DateTime
from obs import Rule
from obs import Lifecycle
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Configure a lifecycle rule for deleting objects with prefix1 as the prefix after 60 days since the last update.
    rule1 = Rule(id='rule1', prefix='prefix1', status='Enabled', expiration=Expiration(days=60))
    # Configure a lifecycle rule for deleting objects with prefix2 as the prefix on December 31, 2023.
    rule2 = Rule(id='rule2', prefix='prefix2', status='Enabled', expiration=Expiration(date=DateTime(2023, 12, 31)))
    lifecycle = Lifecycle(rule=[rule1, rule2])
    bucketName="examplebucket"
    # Configures the lifecycle rules for the bucket.
    resp = obsClient.setBucketLifecycle(bucketName, lifecycle)
    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Set Bucket Lifecycle Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Set Bucket Lifecycle Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Set Bucket Lifecycle Failed')
    print(traceback.format_exc())

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback