【问题标题】:Upload File to AWS S3 from AppEngine using boto3使用 boto3 从 AppEngine 将文件上传到 AWS S3
【发布时间】:2017-07-21 10:36:43
【问题描述】:

如何将文件从我的 AppEngine 应用程序上传到 AWS S3?用户提交文件上传表单并从 AppEngine 应用程序,使用 python 我必须将文件上传到 S3。

class FileUpload(webapp2.RequestHandler):
    def post(self):
        file_data = self.request.POST['file']

要将文件对象上传到 S3,我们必须使用open 方法。 Boto Docuement

with open('filename', 'rb') as data:
    s3.upload_fileobj(data, 'mybucket', 'mykey')

那么在这里我如何使用open 方法访问file_data 对象?

【问题讨论】:

  • 为什么不上传到谷歌自己的Cloud Storage
  • 由于特定的架构设计,我们不得不使用S3而不是GCS。
  • 根据boto3.readthedocs.io/en/latest/reference/services/…,您只需要确保file_data 是字节类型。然后你可以直接使用 s3.upload_fileobj(file_data, 'mybucket', 'mykey') 来上传你的数据。
  • @kakashi 但是如何替换 with open

标签: python google-app-engine amazon-s3 boto3 webapp2


【解决方案1】:

您应该可以省略with open 部分。根据Boto docs you linked to,您需要一个“类文件对象”作为s3.upload_fileobj() 的第一个参数。请记住 self.request.POST['file'] 返回一个cgi.FieldStorage 对象,您可以像这样获得类似文件的对象(source):

field_storage_obj = self.request.POST.get('file')
file_like_obj = self.request.POST.get('file').file
# or: file_like_obj = field_storage_obj.file

file_like_obj实际上是StringIO的一个实例,它具有类文件对象的Boto所需的.read()方法。所以你的最终代码如下所示:

class FileUpload(webapp2.RequestHandler):
    def post(self):
        file_data = self.request.POST['file'].file
        s3.upload_fileobj(file_data, 'mybucket', 'mykey')

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多