[英]Creating a new file, writing to it and uploading to S3 using Python in Lambda
[英]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
可能不是最好的方法。 任何指导?
另外,我试过用wb
和w
而不是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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.