【问题标题】:Reading data from S3 using Lambda使用 Lambda 从 S3 读取数据
【发布时间】:2016-02-20 08:40:26
【问题描述】:

我有一系列 json 文件存储在 AWS 上的 S3 存储桶中。

我希望使用 AWS lambda python 服务来解析这个 json 并将解析结果发送到 AWS RDS MySQL 数据库。

我有一个稳定的 python 脚本用于解析和写入数据库。我需要 lambda 脚本来遍历 json 文件(当它们被添加时)。

每个json文件都包含一个列表,简单的由results = [content]组成

在伪代码中我想要的是:

  1. 连接到 S3 存储桶 (jsondata)
  2. 读取 JSON 文件的内容 (results)
  3. 为此数据执行我的脚本 (results)

我可以通过以下方式列出我拥有的存储桶:

import boto3

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)

给予:

jsondata

但我无法访问此存储桶以读取其结果。

似乎没有readload 函数。

我想要类似的东西

for bucket in s3.buckets.all():
   print(bucket.contents)

编辑

我误解了一些东西。 lambda 必须自行下载,而不是在 S3 中读取文件。

here看来你必须给lambda一个下载路径,它可以从中访问文件本身

import libraries

s3_client = boto3.client('s3')

def function to be executed:
   blah blah

def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key'] 
        download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)
        s3_client.download_file(bucket, key, download_path)

【问题讨论】:

    标签: python json amazon-web-services amazon-s3 aws-lambda


    【解决方案1】:
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket=bucket, Key=key)
    emailcontent = response['Body'].read().decode('utf-8')
    

    【讨论】:

    • 还应注意,您需要创建一个 s3 对象以在您的响应中使用。即s3 = boto3.client('s3')
    【解决方案2】:

    您可以使用bucket.objects.all() 获取存储桶中所有对象的列表(您还可以根据需要使用filterpage_sizelimit 等替代方法)

    这些方法返回一个包含S3.ObjectSummary 对象的迭代器,从那里您可以使用方法object.get 来检索文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2015-06-16
      • 2020-04-13
      • 2016-10-09
      相关资源
      最近更新 更多