How to upload a file to S3 without creating a temporary local file

前端 未结 10 1701
無奈伤痛
無奈伤痛 2021-01-30 13:49

Is there any feasible way to upload a file which is generated dynamically to amazon s3 directly without first create a local file and then upload to the s3 server? I use python.

10条回答
  •  野的像风
    2021-01-30 14:30

    def upload_to_s3(url, **kwargs):
        '''
        :param url: url of image which have to upload or resize to upload
        :return: url of image stored on aws s3 bucket
        '''
    
        r = requests.get(url)
        if r.status_code == 200:
            # credentials stored in settings AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
            conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, host=AWS_HOST)
    
            # Connect to bucket and create key
            b = conn.get_bucket(AWS_Bucket_Name)
            k = b.new_key("{folder_name}/{filename}".format(**kwargs))
    
            k.set_contents_from_string(r.content, replace=True,
                                       headers={'Content-Type': 'application/%s' % (FILE_FORMAT)},
                                       policy='authenticated-read',
                                       reduced_redundancy=True)
    
            # TODO Change AWS_EXPIRY
            return k.generate_url(expires_in=AWS_EXPIRY, force_http=True)
    

提交回复
热议问题