我在 Python Web 环境中工作,我可以使用 boto 的 key.set_contents_from_filename(path/to/file) 将文件从文件系统上传到 S3。但是,我想上传一张已经在网络上的图片(比如 https://pbs.twimg.com/media/A9h_htACIAAaCf6.jpg:large)。
我应该以某种方式将图像下载到文件系统,然后像往常一样使用 boto 将其上传到 S3,然后删除图像吗?
理想的情况是,如果有一种方法可以获取 boto 的 key.set_contents_from_file 或其他可以接受 URL 并将图像很好地流式传输到 S3 而无需将文件副本显式下载到我的服务器的命令。
def upload(url):
try:
conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
bucket = conn.get_bucket(bucket_name)
k = Key(bucket)
k.key = "test"
k.set_contents_from_file(url)
k.make_public()
return "Success?"
except Exception, e:
return e
使用 set_contents_from_file,如上所述,我收到“字符串对象没有属性 'tell'”错误。将 set_contents_from_filename 与 url 一起使用,我得到一个 No such file or directory 错误。 boto storage documentation没有提到上传本地文件,也没有提到上传远程存储的文件。
最佳答案
这是我使用 requests 的方法,关键是在最初发出请求时设置 stream=True
,并使用 upload.fileobj()
方法上传到 s3:
import requests
import boto3
url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg"
r = requests.get(url, stream=True)
session = boto3.Session()
s3 = session.resource('s3')
bucket_name = 'your-bucket-name'
key = 'your-key-name' # key is the name of file on your bucket
bucket = s3.Bucket(bucket_name)
bucket.upload_fileobj(r.raw, key)
关于python - 使用 boto 将公共(public) URL 上可用的图像上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346065/