【问题标题】:Is is possible to read a file from S3 in Google App Engine using boto?是否可以使用 boto 从 Google App Engine 中的 S3 读取文件?
【发布时间】:2011-04-26 07:00:02
【问题描述】:

我想在 Google App Engine 的沙箱中操作存储在 S3 中的腌制 python 对象。我使用boto的documentation中的建议:

from boto.s3.connection import S3Connection

from boto.s3.key import Key

conn = S3Connection(config.key, config.secret_key)
bucket = conn.get_bucket('bucketname')
key = bucket.get_key("picture.jpg")
fp = open ("picture.jpg", "w")
key.get_file (fp)

但这需要我写入一个文件,这在 GAE 沙箱中显然不是犹太教。

我该如何解决这个问题? 非常感谢您的帮助

【问题讨论】:

    标签: python google-app-engine amazon-s3 amazon-web-services boto


    【解决方案1】:

    您根本不需要写入文件或 StringIO。您可以调用key.get_contents_as_string() 将密钥的内容作为字符串返回。密钥的文档是here

    【讨论】:

    • 感谢尼克。这有效,无需导入 StringIO 模块。我认为出于显而易见的原因,这使其成为更好的解决方案。对于在家跟随的任何人,我将 pickle.load(content) 更改为 pickle.loads(content) 以解开类似字符串而不是类似文件的对象。
    • 我还建议在 get_bucket 调用中使用 validate=False - 即 bucket = conn.get_bucket(bucket_name, validate=False) 作为 boto 尝试访问存储桶,如果不这样做会失败无权这样做。欲了解更多信息,请参阅:stackoverflow.com/questions/12571217/…
    • 另外,boto 键有一个可以使用的 .open() 调用。
    【解决方案2】:

    您可以写入 blob 并使用 StringIO 检索数据

    from boto.s3.connection import S3Connection
    from boto.s3.key import Key
    from google.appengine.ext import db
    
    class Data(db.Model)
        image = db.BlobProperty(default=None)
    
    conn = S3Connection(config.key, config.secret_key)
    bucket = conn.get_bucket('bucketname')
    key = bucket.get_key("picture.jpg")
    fp = StringIO.StringIO()
    key.get_file(fp)
    
    data = Data(key_name="picture.jpg")
    data.image = db.Blob(fp.getvalue())
    data.put()
    

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 2011-05-09
      • 2013-03-25
      • 2012-05-08
      • 2013-01-26
      • 2017-09-07
      • 2018-07-22
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多