python - 使用 boto 将公共(public) URL 上可用的图像上传到 S3

标签 python django amazon-s3 boto

我在 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/

相关文章:

django - redis 正在运行,但我得到 "Error 111 connecting to localhost:6379. Connection refused"

django - 通过django s3中间件保存文件时获取Http403(但可以在shell中使用boto保存)

amazon-s3 - 在同一个存储桶中移动多个文件

python - 将字符串转换为日期时间对象

python - 使用 lxml 解析 Yelp - 忽略 html 标签

python - Django REST 框架 : SlugRelatedField for indirectly-related attribute?

python - Django QuerySet 按 ID 自定义排序

amazon-web-services - 使用 s3fs 时, 'ls' 命令不显示任何内容

python - Tcl错误: couldn't recognize data in image file "background.png"

python - 关键词多词时高效搜索关键词