
Python
Amazon S3 - 如何检查预签名 URL 是否过期?
Amazon Simple Storage Service(S3)是一种可扩展的云存储解决方案,可以帮助开发人员存储和检索任意数量的数据。预签名 URL 是一种用于授权临时访问 S3 对象的机制。在某些情况下,我们可能需要检查预签名 URL 是否过期,以确保安全性和有效性。本文将介绍如何 预签名 URL,并通过案例代码演示如何检查预签名 URL 是否过期。生成预签名 URL要生成预签名 URL,我们可以使用 AWS SDK 或 AWS CLI 工具。以下是使用 AWS SDK for Python(Boto3)生成预签名 URL 的示例代码:Pythonimport boto3from botocore.exceptions import ClientErrorfrom datetime import datetime, timedeltadef generate_presigned_url(bucket_name, object_name, expiration=3600): """ 生成预签名 URL :param bucket_name: S3 存储桶名称 :param object_name: S3 对象名称 :param expiration: URL 有效期(以秒为单位),默认为 1 小时 :return: 预签名 URL """ s3_client = boto3.client('s3') try: response = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_name}, ExpiresIn=expiration) except ClientError as e: print(e) return None return response以上代码中,我们使用 boto3.client('s3') 创建了 S3 客户端对象,并使用 generate_presigned_url 方法生成预签名 URL。我们需要提供 S3 存储桶名称和对象名称,以及可选的 URL 有效期。方法将返回生成的预签名 URL。检查预签名 URL 是否过期为了检查预签名 URL 是否过期,我们可以使用 datetime 模块获取当前时间,并与预签名 URL 中的过期时间进行比较。以下是检查预签名 URL 是否过期的示例代码:Pythondef is_presigned_url_expired(presigned_url): """ 检查预签名 URL 是否过期 :param presigned_url: 预签名 URL :return: 是否过期(True/False) """ expiration_string = presigned_url.split('Expires=')[1].split('&')[0] expiration_time = datetime.fromisoformat(expiration_string) current_time = datetime.now() if current_time > expiration_time: return True return False上述代码中,我们首先从预签名 URL 中提取过期时间,并使用 datetime.fromisoformat 方法将其转换为 datetime 对象。然后,我们获取当前时间,并将其与过期时间进行比较。如果当前时间晚于过期时间,则预签名 URL 已过期。案例代码下面是一个完整的案例代码,演示了如何生成预签名 URL 并检查其是否过期:Pythonimport boto3from botocore.exceptions import ClientErrorfrom datetime import datetime, timedeltadef generate_presigned_url(bucket_name, object_name, expiration=3600): """ 生成预签名 URL :param bucket_name: S3 存储桶名称 :param object_name: S3 对象名称 :param expiration: URL 有效期(以秒为单位),默认为 1 小时 :return: 预签名 URL """ s3_client = boto3.client('s3') try: response = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_name}, ExpiresIn=expiration) except ClientError as e: print(e) return None return responsedef is_presigned_url_expired(presigned_url): """ 检查预签名 URL 是否过期 :param presigned_url: 预签名 URL :return: 是否过期(True/False) """ expiration_string = presigned_url.split('Expires=')[1].split('&')[0] expiration_time = datetime.fromisoformat(expiration_string) current_time = datetime.now() if current_time > expiration_time: return True return False# 示例用法bucket_name = 'my-bucket'object_name = 'my-object'expiration_time = 3600presigned_url = generate_presigned_url(bucket_name, object_name, expiration_time)print("生成的预签名 URL:", presigned_url)if is_presigned_url_expired(presigned_url): print("预签名 URL 已过期")else: print("预签名 URL 有效")本文介绍了如何 Amazon S3 的预签名 URL,并演示了如何检查预签名 URL 是否过期。通过生成预签名 URL,我们可以授权临时访问 S3 对象,并通过检查过期时间来确保安全性和有效性。预签名 URL 提供了一种灵活且安全的方式来共享和访问 S3 中的对象。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号