【问题标题】:reading and writing excel files from s3 using boto3 in lambda在 lambda 中使用 boto3 从 s3 读取和写入 excel 文件
【发布时间】:2018-10-10 06:26:24
【问题描述】:

我正在尝试从一个 s3 存储桶中读取一个 excel 文件,并使用 aws lambda 中的 boto3 将其写入另一个存储桶。我已经为我的角色提供了完整的 s3 访问权限并编写了以下代码

import boto3
import botocore
import io
def lambda_handler(event, context):
    s3 = boto3.resource('s3')
    s3.Bucket('<first_bucket>').download_file('<file_name>.xlsx', '/tmp/<file_name>.xlsx')
    object = s3.Object('<first_bucket>','<file_name>.xlsx')
    with open('/tmp/<file_name>', 'wb') as data:
        object.download_fileobj(data)
    target_object =  s3.Object('<second_bucket>','<file_name>.xlsx')
    target_object.put(data)


    return 'Successfully written to new bucket'

我在 Lambda 中执行了此代码,当我检查我的第二个存储桶时,我可以看到该文件存在,但它的大小为 0。我不确定为什么以及如何更正此问题。有什么指点吗?

【问题讨论】:

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


    【解决方案1】:

    Boto 提供了copy_from 函数来直接将对象复制到另一个位置。这避免了手动下载文件的需要。

    target_object.copy_from(CopySource='from_bucket/from_file')
    

    您可以使用它或确保您正在读取的文件已打开并位于第一个字节。在上面的sn-p中,文件在with语句之后已经被关闭了。

    with open('/tmp/file', 'rb') as file:
        target_object.put(Body=file)
    

    或者通过寻找开头重用相同的文件句柄:

    file.seek(0)
    target_object.put(Body=file)
    

    【讨论】:

    • 您之前使用 target_object.put(Body = open('/tmp/file', 'rb')) 的建议正在起作用,但是,您当前的答案仍然给我大小为 0 的文件。跨度>
    • 尝试使用 Body=file
    • 谢谢。现在很好用
    【解决方案2】:

    您存储在本地的临时文件,您没有引用它。 以下代码应该适合您。

    import boto3
    import botocore
    import io
     def lambda_handler(event, context):
      s3 = boto3.resource('s3')
       s3.Bucket('<first_bucket>').download_file('<file_name>.xlsx', '/tmp/<file_name>.xlsx')
    
    //upload start from here
    
    s3 = boto3.resource('s3')
    s3.meta.client.upload_file('/tmp/<file_name>.xlsx', '<second_bucket>', '/path/to/bucket/<file_name>.xlsx')
    return 'Successfully written to new bucket'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多