Using boto3.client in fastapi project

  Kiến thức lập trình
class S3Service:
    """
    A helper class for interacting with AWS S3.

    Parameters
    ----------
    `aws_access_key_id (str)`: 
        AWS access key ID.
    `aws_secret_access_key (str)`: 
        AWS secret access key.
    """

    def __init__(self, aws_access_key_id, aws_secret_access_key):
        self.aws_access_key_id = aws_access_key_id
        self.aws_secret_access_key = aws_secret_access_key
        self.client = self._create_s3_client()
    
    def _create_s3_client(self):
        return boto3.client('s3',
                            aws_access_key_id=self.aws_access_key_id,
                            aws_secret_access_key=self.aws_secret_access_key)

    def _handle_info_response(self, response: dict) -> bool:
        status_code = response.get(
            "ResponseMetadata", {}).get("HTTPStatusCode", 0)
        return status_code in [200, 204]

    def upload_fileobj(self, bucket, key, data):
        file_upload_response = self.client.put_object(
            Bucket=bucket, Key=key, Body=data)
        return self._handle_info_response(
            file_upload_response,
            f"File uploaded path: https://{bucket}.s3.amazonaws.com/{key}",
            "File upload failed."
        )

When I initialize this class in a FastAPI project, each user will use the same S3Service instance. Since I want to isolate users from each other, I am concerned about the possibility of responses from different users interfering with each other. Could such a situation occur? What would be the correct approach? Should I initialize a new instance for each user? Would using different instances for each user cause performance issues?

Isolating users from each other would be helpful, if you, for example, store specific metadata for each user in your S3Service, or if your users provided their own aws_access_key_id and aws_secret_access_key, but, as I understand, you are using your own s3 account each time, and don’t store any specific metadata in your S3Service for each user, so I couldn’t see, why you would need such isolation.

Could you provide more details, why do you want to isolate S3Services?

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT