【问题标题】:Is there way to stream CSV object from S3 bucket to AWS lambda using boto3?有没有办法使用 boto3 将 CSV 对象从 S3 存储桶流式传输到 AWS lambda?
【发布时间】:2019-09-28 17:24:52
【问题描述】:

有没有办法使用 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,对吗? (顺便说一句,您的代码在定义之前引用了NameAge。)如果您可以编辑您的问题以告诉我们您的实际目标,我们更有可能提供好的建议。跨度>
  • 您尝试过使用流 API 吗?
  • 我最终使用了 smart_open。这里是 smart_open 的链接:github.com/RaRe-Technologies/smart_open

标签: json csv amazon-s3 aws-lambda boto3


【解决方案1】:

对于来自 S3 中 CSV/JSON 文件的流式数据,您可以使用“S3 Select”。使用它,您可以将数据直接流式传输到您的代码并使用它,而不是在内存中下载文件并进行处理。

除此之外,您还可以对代码执行基本的 SQL 语句。

您也可以参考此代码进行参考:https://gist.github.com/SrushithR/1dbb6d3521383c259b47756506cf5955

【讨论】:

    【解决方案2】:

    我最终使用了 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)
    

    您可以在 s3 存储桶中打开一个文件,其 URL 如下所示:s3://my_bucket/my_key

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多