Python boto3验证会话

2024-10-01 00:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我需要将文件上载到S3时,我都会运行以下代码:

client = boto3.session.Session().client(self.client_type, use_ssl=True)
# use the client to upload

然而,这意味着每次需要上传文件时,我都会请求对S3进行身份验证。在我的例子中,如果会话仍然为同一个客户端打开,我想共享很多文件,但是我找不到通过boto3检测会话是否仍然有效的方法,有方法吗

目前,我正在我的应用程序中跟踪1小时的时间,以便执行以下操作:

class ArchiveStorage(object):

    client = None
    session_duration_seconds = 60 * 60  # One Hour
    client_type = "s3"
    last_session = None

    def __init__(self):
        if ArchiveStorage.client is None or not self._is_session_valid():
            ArchiveStorage.client = self._create_new_s3_session()
        self.client = ArchiveStorage.client

    def _create_new_s3_session(self):
        return boto3.session.Session().client(self.client_type, use_ssl=True)

    def _is_session_valid(self):
        if not self.last_session:
            return False
        now = get_logical_timestamp()
        if now - ArchiveStorage.last_session > self.session_duration_seconds:
            return False
        return True

是否有一种方法可以验证S3会话,而不需要在应用程序端计算会话时间


Tags: 文件方法selfclientnonetruereturns3