在Python中使用Lambda和AW将文件写入S3

2024-04-27 03:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在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中,有一个buckettransportation.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.documentation建议使用“rb”,但我不明白为什么会这样。

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


Tags: 文件csvthekeydatas3bucketresponse
2条回答

假设Python 3.6。我通常这样做的方式是将字节内容包装在BytesIO包装器中,以创建类似文件的对象。而且,根据boto3文档,您可以使用the-transfer-manager进行托管传输:

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

fileobj = BytesIO(response.content)

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

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

您有一个可写的流,您要求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)

相关问题 更多 >