有没有办法使用boto3来回传输到AWS lambda?我有一个工作代码,但是将CSV数据加载到内存过程中,并将其放入S3对象中。我宁愿寻找一种使用BOTO3从S3流式对象并将其流回S3的方法。
import csv
import json
import boto3
def lambda_handler(event, context):
targetbucket = 'AWS_BUCKET_NAME'
csvkey = 'CSV_FILENAME.csv'
jsonkey = 'JSON_FILENAME.json'
s3 = boto3.resource('s3')
csv_object = s3.Object(targetbucket, csvkey)
csv_content = csv_object.get()['Body'].read().splitlines()
s3_client = boto3.client('s3')
result = []
for line in csv_content:
x = json.dumps(line.decode('utf-8')).split(',')
Name = str(x[0])
Title = str(x[1])
Age = str(x[2])
jsonData = '{ "Name": ' + Name + '"' + ','
+ ' "Title": ' + '"' + Title + '"' + ','
+ ' "Age": ' + '"' + Age + '"' + '}'
result.append(jsonData)
s3_client.put_object(
Bucket=targetbucket,
Body= str(result).replace("'",""),
Key=jsonkey
)
用于从S3中的CSV/JSON文件流数据,您可以使用's3 select'。使用此功能,您将数据直接流传输到您的代码并使用它,而不是在内存中下载文件并处理它。
除此之外,您还可以在代码上执行基本的SQL语句。
您也可以参考参考文献:https://gist.github.com/srushithr/1dbb6d3521383c259b4777777756506cf5955
我最终使用smart_open:https://github.com/rare-technologies/smart_open,这是其readme的示例。
>>> # can use context managers too:
>>> with open('smart_open/tests/test_data/1984.txt.gz') as fin:
... with open('smart_open/tests/test_data/1984.txt.bz2', 'w') as fout:
... for line in fin:
... fout.write(line)
您可以用看起来像这样的URL打开S3存储桶中的文件:s3://my_bucket/my_key