sus*_*nne 25 python amazon amazon-s3
是否有任何可行的方法可以直接上传动态生成的文件到amazon s3而无需先创建本地文件然后上传到s3服务器?我用python.谢谢
Jim*_*Jty 23
下面是一个下载图像(使用请求库)并将其上传到s3的示例,无需写入本地文件:
import boto
from boto.s3.key import Key
import requests
#setup the bucket
c = boto.connect_s3(your_s3_key, your_s3_key_secret)
b = c.get_bucket(bucket, validate=False)
#download the file
url = "http://en.wikipedia.org/static/images/project-logos/enwiki.png"
r = requests.get(url)
if r.status_code == 200:
#upload the file
k = Key(b)
k.key = "image1.png"
k.content_type = r.headers['content-type']
k.set_contents_from_string(r.content)
Run Code Online (Sandbox Code Playgroud)
Roy*_*Han 15
您可以使用Python标准库中的BytesIO.
from io import BytesIO
bytesIO = BytesIO()
bytesIO.write('whee')
bytesIO.seek(0)
s3_file.set_contents_from_file(bytesIO)
Run Code Online (Sandbox Code Playgroud)
jte*_*ace 11
有关使用set_contents_from_string的示例,请参阅boto文档的存储数据部分,粘贴在此处是为了完整性:
>>> from boto.s3.key import Key
>>> k = Key(bucket)
>>> k.key = 'foobar'
>>> k.set_contents_from_string('This is a test of S3')
Run Code Online (Sandbox Code Playgroud)
我假设你正在使用boto. boto'sBucket.set_contents_from_file()将接受一个StringIO对象,并且您编写的用于将数据写入文件的任何代码都应该很容易适应写入对象StringIO。或者,如果您生成字符串,则可以使用set_contents_from_string().