【问题标题】:AWS lambda function to write csv data to an Amazon DynamoDB table用于将 csv 数据写入 Amazon DynamoDB 表的 AWS lambda 函数
【发布时间】:2021-08-28 00:06:53
【问题描述】:

以下是在将 csv 文件上传到 Amazon S3 存储桶并将数据写入 Amazon DynamoDB 表时触发 lambda 函数的代码。我收到错误“预期的 str、字节或 os.PathLike 对象,而不是 dict”。

能否请您指出我犯的错误在哪里。

import boto3
import csv

s3_client = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
#table = dynamodb.Table('batch_data')

def csv_write(table_name, rows):
    table = dynamodb.Table(table_name)

    with table.csv_write() as batch:
        for row in rows:
            batch.put_item(Item=row)
    return True

def read_csv(csv_file, list):
    rows = csv.DictReader(open(csv_file))

    for row in rows:
        list.append(row)

def lambda_handler(event, context):
    try:

        bucket = event['Records'][0]['s3']['bucket']['name']
        csv_file_name = event['Records'][0]['s3']['object']['key']
        response = s3_client.get_object(Bucket=bucket, Key= csv_file_name)

        table_name = 'batch_data'
        items = []

        read_csv(response, items)
        status = csv_write(table_name, items)

        if(status):
            print('Data saved')
        else:
            print('Error in saving data...')
    except Exception as err:
        print (err)
    ```

【问题讨论】:

  • 错误究竟来自哪里?
  • 我认为您正在关注 youtube 教程,mka 一定要检查您的 csv 文件的数据类型

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


【解决方案1】:

您的存储桶或 csv_file_name 可能无意中是一本字典,即您没有用尽事件的层次结构

【讨论】:

    【解决方案2】:

    这一行:

    response = s3_client.get_object(Bucket=bucket, Key= csv_file_name)
    

    返回一个像这样的对象:

    {
        'Body': StreamingBody(),
        'LastModified': datetime(2015, 1, 1),
        'ContentLength': 123,
        ...
    }
    

    这一行:

    read_csv(response, items)
    

    response 作为 csv_file 传递给此函数:

    def read_csv(csv_file, list):
        rows = csv.DictReader(open(csv_file))
        ...
    

    但是,open() 命令不知道如何解释来自 S3 的响应对象。这就是它返回错误的原因:

    预期的 str、字节或 os.PathLike 对象,而不是 dict

    根据来自How do I read a csv stored in S3 with csv.DictReader? 的信息,我得到了这段代码:

    import boto3
    import csv
    
    def lambda_handler(event, context):
        
        s3_client = boto3.client('s3')
        
        bucket = event['Records'][0]['s3']['bucket']['name']
        csv_file_name = event['Records'][0]['s3']['object']['key']
        
        response = s3_client.get_object(Bucket=bucket, Key= csv_file_name)
    
        lines = response['Body'].read().decode('utf-8').split()
        for row in csv.DictReader(lines):
            print(row)
    

    您可以使用该方法从StreamingBody 读取CSV,该CSV 从get_object() 返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多