繁体   English   中英

使用带有AWS的Python中的Lambda将文件写入S3

[英]Writing a file to S3 using Lambda in Python with AWS

在AWS中,我正在尝试使用Lambda函数将文件保存到Python中的S3。 虽然这适用于我的本地计算机,但我无法在Lambda中使用它。 我一直在大部分时间都在研究这个问题并且会感谢你的帮助。 谢谢。

def pdfToTable(PDFfilename, apiKey, fileExt, bucket, key):

    # parsing a PDF using an API
    fileData = (PDFfilename, open(PDFfilename, "rb"))
    files = {"f": fileData}
    postUrl = "https://pdftables.com/api?key={0}&format={1}".format(apiKey, fileExt)
    response = requests.post(postUrl, files=files)
    response.raise_for_status()

    # this code is probably the problem!
    s3 = boto3.resource('s3')
    bucket = s3.Bucket('transportation.manifests.parsed')
    with open('/tmp/output2.csv', 'rb') as data:
        data.write(response.content)
        key = 'csv/' + key
        bucket.upload_fileobj(data, key)

    # FYI, on my own computer, this saves the file
    with open('output.csv', "wb") as f:
        f.write(response.content)

在S3中,有一个bucket transportation.manifests.parsed其中包含应保存文件的文件夹csv

response.content的类型是字节。

从AWS,上面当前设置的错误是[Errno 2] No such file or directory: '/tmp/output2.csv': FileNotFoundError. 实际上,我的目标是以唯一名称将文件保存到csv文件夹,因此tmp/output2.csv可能不是最好的方法。 任何指导?

另外,我试过用wbw而不是rb也无济于事。 wb的错误是Input <_io.BufferedWriter name='/tmp/output2.csv'> of type: <class '_io.BufferedWriter'> is not supported. 文档建议使用'rb'是推荐用法,但我不明白为什么会出现这种情况。

另外,我尝试过s3_client.put_object(Key=key, Body=response.content, Bucket=bucket)但是An error occurred (404) when calling the HeadObject operation: Not Found收到An error occurred (404) when calling the HeadObject operation: Not Found

你有一个可写的流,你要求boto3用作一个无法使用的可读流。

编写文件,之后只需使用bucket.upload_file(),如下所示:

s3 = boto3.resource('s3')
bucket = s3.Bucket('transportation.manifests.parsed')
with open('/tmp/output2.csv', 'w') as data:
    data.write(response.content)

key = 'csv/' + key
bucket.upload_file('/tmp/output2.csv', key)

假设Python 3.6。 我通常这样做的方法是将字节内容包装在BytesIO包装器中以创建像object这样的文件。 而且,根据boto3文档,您可以使用-trans -manager进行托管转移:

from io import BytesIO
import boto3
s3 = boto3.client('s3')

fileobj = BytesIO(response.content)

s3.upload_fileobj(fileobj, 'mybucket', 'mykey')

如果这不起作用,我会仔细检查所有IAM权限是否正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM