首页 > 解决方案 > 从 S3 读取时 AWS Lambda 函数出错

问题描述

我正在尝试从 S3 存储桶中读取一个 excel 文件。这是我的 Lambda 函数代码,但在我使用pd.read_excel.

我无法弄清楚这个问题,因为语法对我来说很好。读取数据有问题吗?请帮忙。

import json
import boto3
import pandas as pd
import io


def lambda_handler(event, context):
    
    s3 = boto3.client("s3")
    s3_resource = boto3.resource("s3")
    
    if event:
        
        s3_records = event["Records"][0]
        bucket_name = str(s3_records["s3"]["bucket"]["name"])
        file_name = str(s3_records["s3"]["object"]["key"])
        
        file_obj = s3.get_object(Bucket=bucket_name, Key=file_name)
        file_content = file_obj["Body"].read()
        
        df = pd.read_excel(io.BytesIO(file_content, engine='xlrd')
          
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

这是日志:

[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 23)
Traceback (most recent call last):
  File "/var/task/lambda_function.py" Line 23
        return {

标签: pandasamazon-web-servicesamazon-s3aws-lambda

解决方案


看来您在return声明之前缺少右括号,应该是这样的:

df = pd.read_excel(io.BytesIO(file_content, engine='xlrd'))

而不是这个

df = pd.read_excel(io.BytesIO(file_content, engine='xlrd')

推荐阅读