How to upload a file to S3 without creating a temp

2020-05-14 16:06发布

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. Thanks

10条回答
叼着烟拽天下
2楼-- · 2020-05-14 16:33

You could use BytesIO from the Python standard library.

from io import BytesIO
bytesIO = BytesIO()
bytesIO.write('whee')
bytesIO.seek(0)
s3_file.set_contents_from_file(bytesIO)
查看更多
【Aperson】
3楼-- · 2020-05-14 16:41
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)
查看更多
Ridiculous、
4楼-- · 2020-05-14 16:44

Given that encryption at rest is a much desired data standard now, smart_open does not support this afaik

查看更多
smile是对你的礼貌
5楼-- · 2020-05-14 16:46

You can try using smart_open (https://pypi.org/project/smart_open/). I used it exactly for that: writing files directly in S3.

查看更多
疯言疯语
6楼-- · 2020-05-14 16:52

Update for boto3:

aws_session = boto3.Session('my_access_key_id', 'my_secret_access_key')
s3 = aws_session.resource('s3')
s3.Bucket('my_bucket').put_object(Key='file_name.txt', Body=my_file)
查看更多
劫难
7楼-- · 2020-05-14 16:55

The boto library's Key object has several methods you might be interested in:

For an example of using set_contents_from_string, see Storing Data section of the boto documentation, pasted here for completeness:

>>> from boto.s3.key import Key
>>> k = Key(bucket)
>>> k.key = 'foobar'
>>> k.set_contents_from_string('This is a test of S3')
查看更多
登录 后发表回答