Bootstrap

aws_S3 文件上传下载

# -*- coding:utf-8 -*-
import boto3
from botocore.client import Config
import logging
from botocore.exceptions import ClientError
from info.constants import ACCESS_KEY_ID,ACCESS_KEY_SECRET,BUCKET_NAME,ENDPOINT

# 上传apk文件
class S3Handler(object):

    def __init__(self):

        self.access_key_id = ACCESS_KEY_ID  # id
        self.access_key_secret = ACCESS_KEY_SECRET #秘钥
        self.bucket_name = BUCKET_NAME # 桶名
        self.endpoint = ENDPOINT
        self.s3 = boto3.resource('s3',aws_access_key_id=self.ACCESS_KEY_ID,aws_secret_access_key=self.ACCESS_SECRET_KEY,
                                 config=Config(signature_version='s3v4'))

        self.s3Client = boto3.client('s3',config=boto3.session.Config(signature_version='s3v4',
                                                                      # region_name='eu-central-1',
                                                                      aws_access_key_id=self.ACCESS_KEY_ID,
                                                                      aws_secret_access_key=self.ACCESS_SECRET_KEY,)),




    def save(self, fpath, data):
        # 上传
        # data 二进制数据
        self.s3.Bucket(self.bucket_name).put_object(Key=fpath, Body=data)

    def create_presigned_url(self,bucket_name, object_name, expiration=3600):
        """
        Generate a presigned URL to share an S3 object
        获取文件临时下载url
        :param bucket_name: string
        :param object_name: string
        :param expiration: Time in seconds for the presigned URL to remain valid
        :return: Presigned URL as string. If error, returns None.
        """

        # Generate a presigned URL for the S3 object
        try:
            response = self.s3Client.generate_presigned_url('get_object',
                                                        Params={'Bucket': bucket_name,
                                                                'Key': object_name},
                                                        ExpiresIn=expiration)
        except ClientError as e:
            logging.error(e)
            return None

        # The response contains the presigned URL
        return response

个人总结:
1.signature_version=‘s3v4’ 这个是重点,不然下载url不能打开
2.未实现在不公开桶内下载连接,具体原因尚未清楚
3.重点了解 IAM 相关策略配置

;