python - 将图像上传到 S3 (boto + GAE)

标签 python google-app-engine boto

我正在尝试使用我的 GAE python 应用程序设置 s3(使用 boto)来存储用户上传的图像。目前我收到以下错误:

File "/Users/phyzikz/project/boto/s3/key.py", line 936, in set_contents_from_file spos = fp.tell()
AttributeError: 'str' object has no attribute 'tell'

我不知道为什么会这样——上传的文件应该是 png。这是进行上传的代码:

class Settings(Handler):
    def get(self):
        self.render('settings.html')

    def post(self):
        image = self.request.get('image')

        if image:
            connection = S3Connection('<ak>','<sak>')
            bucket = connection.create_bucket('<s3bucket>')
            k = Key(bucket)
            k.key = '/pictures/users/'+ str(self.user.key().id())
            k.set_contents_from_file(image)

如果有帮助,在调试时将 set_contents_from_file(image) 替换为 set_contents_from_string('some string') 时效果很好。我一定错过了一些简单的东西。这是 html:

<form method='post' action='/settings' enctype='multipart/form-data'>
    <input type='file' name='image'>
    <input type='submit'>
</form>

免责声明:我是 python 和 SO 的新手(这是我的第一个问题!)如有必要,我们将不胜感激任何改进问题措辞的编辑。

最佳答案

您需要将图像包装在 StringIO 实例中,使其看起来像一个文件对象

Python 2.7.2+ (default, Oct  4 2011, 20:03:08) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = "123"
>>> from StringIO import StringIO
>>> y = StringIO(x)
>>> y.tell()
0
>>> 

所以在你的情况下你会

k.set_contents_from_file(StringIO(image))

关于python - 将图像上传到 S3 (boto + GAE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12336648/

相关文章:

python - 防止成员对象引用同一个列表

python - 谷歌应用引擎: How to Truncate string after a given number of chars

amazon-web-services - 我可以在 boto 中按 instance_id 过滤卷吗?

Python - 处理来自 STDIN 的输入而不转换为整数(SPOJ INOUTEST)

python - 如何使用 python 查看目录中每个文件的第一行

python - 为什么我无法从另一个源文件导入 Django 模型?

python - Django 项目无法强制 Google Appengine 重定向到 https

python - 使用 Google App Engine GQL 查找给定半径内的所有位置

python - 连接关闭错误 : Connection was closed before we received a valid response from endpoint URL:

python - 如何使用 Boto 启动 EC2 实例,指定 EBS 的大小?