【问题标题】:AWS S3 Download and Upload using TemporaryFileAWS S3 使用 TemporaryFile 下载和上传
【发布时间】:2018-09-22 16:09:05
【问题描述】:

我需要下载 Amazon S3 存储桶的所有内容(包括版本)并上传到其他 Amazon S3 存储桶。不要叫我用aws,我就是不会用。

我为此使用了 tempfile.TemporaryFile,它显然有效,打印显示文件对象内部有正确的内容,但 上传 文件是空的(零字节)。

with tempfile.TemporaryFile() as data:
    sourceUser.download_fileobj('source-bucket',key,data)
    # next 2 lines was just to check the content of the file
    data.seek(0)
    print (data.read())
    destinationUser.upload_fileobj(data,'destination-bucket',key)

【问题讨论】:

  • 在上传前重新寻找偏移量0?还是在文件上打开一个新流?
  • 你见过this question吗?
  • @ClaudiuIvanescu 您不必使用任何库直接从一个存储桶复制到另一个存储桶。您可以使用 hmac-sha-256 库和 HTTP 用户代理...或 API Gateway 后面的 Lambda 函数来构建和签署请求并将其发送到 S3。
  • @Michael-sqlbot 很抱歉,我没有足够的知识来做你的事情。 jarmod 显示了错误,现在可以工作了。但我不想拿他的功劳!
  • 这也解决了我遇到的一个问题,我需要下载和重新上传(在我的情况下需要进行 CV2 操作)。 tmp.seek(0) 也在这里解决了我的问题。谢谢@jarmod

标签: python python-3.x amazon-web-services amazon-s3


【解决方案1】:

我也有同样的需求,如何将NamedTemporaryFile传递给上传s3

不确定如何将 NamedTemporaryFileName 传递给 output=f'{file_name}.gpg' 和 load_file 函数 --> filename=f_source.name

with tempFile.NamedTemporaryFile("wb") as f_source:
                s3_client.download_fileobj(s3_bucket, s3_key, f_source)
                logger.info(f'{s3_key} file downloaded successfully to local {f_source}')
                f_source.flush()
                file_name = self.s3_key.split('/')[-1]
                gpg = gnupg.GPG()
                key_data = open(key_path).read()
                import_result = gpg.import_keys(key_data)
                f_source.seek(0)
                with open(f_source.name, 'r+b') as f:
                    status = gpg.encrypt_file(
                        file=f,
                        recipients=[recipient],
                        output=f'{file_name}.gpg',
                    )

                    s3_hook.load_file(
                        filename=f_source.name,
                        key=s3_key,
                        bucket_name=s3_bucket,
                        replace=True
                    )

【讨论】:

  • 您没有临时文件的名称....您的数据内容为 f_source。不要试图重新打开。一定要寻找 0 并随心所欲地保存。
猜你喜欢
  • 2017-03-17
  • 2020-03-23
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 2017-10-17
  • 2012-03-16
  • 1970-01-01
相关资源
最近更新 更多