GetObjectLegalHoldÚselo con un AWS SDK o CLI - Ejemplos de código de AWS SDK

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

GetObjectLegalHoldÚselo con un AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar GetObjectLegalHold.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en los siguientes ejemplos de código:

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Get the legal hold details for an S3 object. /// </summary> /// <param name="bucketName">The bucket of the object.</param> /// <param name="objectKey">The object key.</param> /// <returns>The object legal hold details.</returns> public async Task<ObjectLockLegalHold> GetObjectLegalHold(string bucketName, string objectKey) { try { var request = new GetObjectLegalHoldRequest() { BucketName = bucketName, Key = objectKey }; var response = await _amazonS3.GetObjectLegalHoldAsync(request); Console.WriteLine($"\tObject legal hold for {objectKey} in {bucketName}: " + $"\n\tStatus: {response.LegalHold.Status}"); return response.LegalHold; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tUnable to fetch legal hold: '{ex.Message}'"); return new ObjectLockLegalHold(); } }
  • Para API obtener más información, consulte GetObjectLegalHoldla AWS SDK for .NET APIReferencia.

CLI
AWS CLI

Recupera el estado de retención legal de un objeto

En el siguiente ejemplo de get-object-legal-hold, se recupera el estado de retención legal del objeto especificado.

aws s3api get-object-legal-hold \ --bucket my-bucket-with-object-lock \ --key doc1.rtf

Salida:

{ "LegalHold": { "Status": "ON" } }
  • Para API obtener más información, consulte GetObjectLegalHoldla Referencia de AWS CLI comandos.

Go
SDKpara Go V2
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // GetObjectLegalHold retrieves the legal hold status for an S3 object. func (actor S3Actions) GetObjectLegalHold(ctx context.Context, bucket string, key string, versionId string) (*types.ObjectLockLegalHoldStatus, error) { var status *types.ObjectLockLegalHoldStatus input := &s3.GetObjectLegalHoldInput{ Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(versionId), } output, err := actor.S3Client.GetObjectLegalHold(ctx, input) if err != nil { var noSuchKeyErr *types.NoSuchKey var apiErr *smithy.GenericAPIError if errors.As(err, &noSuchKeyErr) { log.Printf("Object %s does not exist in bucket %s.\n", key, bucket) err = noSuchKeyErr } else if errors.As(err, &apiErr) { switch apiErr.ErrorCode() { case "NoSuchObjectLockConfiguration": log.Printf("Object %s does not have an object lock configuration.\n", key) err = nil case "InvalidRequest": log.Printf("Bucket %s does not have an object lock configuration.\n", bucket) err = nil } } } else { status = &output.LegalHold.Status } return status, err }
  • Para API obtener más información, consulte GetObjectLegalHoldla AWS SDK for Go APIReferencia.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// Get the legal hold details for an S3 object. public ObjectLockLegalHold getObjectLegalHold(String bucketName, String objectKey) { try { GetObjectLegalHoldRequest legalHoldRequest = GetObjectLegalHoldRequest.builder() .bucket(bucketName) .key(objectKey) .build(); GetObjectLegalHoldResponse response = getClient().getObjectLegalHold(legalHoldRequest); System.out.println("Object legal hold for " + objectKey + " in " + bucketName + ":\n\tStatus: " + response.legalHold().status()); return response.legalHold(); } catch (S3Exception ex) { System.out.println("\tUnable to fetch legal hold: '" + ex.getMessage() + "'"); } return null; }
  • Para API obtener más información, consulte GetObjectLegalHoldla AWS SDK for Java 2.x APIReferencia.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Retenga legalmente un objeto.

def get_legal_hold(s3_client, bucket: str, key: str) -> None: """ Get the legal hold status of a specific file in a bucket. Args: s3_client: Boto3 S3 client. bucket: The name of the bucket containing the file. key: The key of the file to get the legal hold status of. """ print() logger.info("Getting legal hold status of file [%s] in bucket [%s]", key, bucket) try: response = s3_client.get_object_legal_hold(Bucket=bucket, Key=key) legal_hold_status = response["LegalHold"]["Status"] logger.debug( "Legal hold status of file [%s] in bucket [%s] is [%s]", key, bucket, legal_hold_status, ) except Exception as e: logger.error( "Failed to get legal hold status of file [%s] in bucket [%s]: %s", key, bucket, e, )
  • Para API obtener más información, consulte GetObjectLegalHoldla AWS SDKreferencia de Python (Boto3). API