首页 > 解决方案 > 无法使用 s3 触发器将 s3 对象传输到 rds

问题描述

我有下面的 lambda 函数代码,它将对象从 s3 存储桶传输到 AWS RDS 数据库。

import json
import boto3
import pymysql 

s3_client = boto3.client('s3')
def lambda_handler(event, context):

bucket_name = event["bucket"]
s3_file_name = event["object"]
resp = s3_client.get_object(Bucket=bucket_name, Key=s3_file_name)

data = resp['Body']
rds_endpoint  = ""
username =  #username for RDS Mysql
password =  # RDS Mysql password
db_name = # RDS MySQL DB name
conn = None
try:
    conn = pymysql.connect(host=rds_endpoint, user=username, password=password, database=db_name)
except pymysql.MySQLError as e:
    print("ERROR: Unexpected error: Could not connect to MySQL instance.")

try:
    cur = conn.cursor()
    cur.execute(#db stuff)
    conn.commit()
except Exception as e:
    print(e)
    return 'Table not created!'
    
with conn.cursor() as cur:
    try:
        cur.execute(#db stuff)
        conn.commit()
        output = cur.execute()
    except:
        output = ("Entry not inputted! Error!")
    
print("Deleting the csv file from s3 bucket")

return {
    'statusCode': 200,
    'body': 'Successfully uploaded!'
}

上面的代码适用于这个给定的测试 ev:

{“桶”:“蟒蛇桶”,“对象”:“bobmarley.mp3”}

但是,当我尝试通过将代码行更改为下面的代码行来使其适应 s3 存储桶时,如本教程中所示:https ://www.data-stats.com/s3-data-ingestion-to-rds-through- λ/

bucket_name = event["Records"][0]["s3"]["bucket"]["name"]
s3_file_name = event["Records"][0]["s3"]["object"]["key"]

我收到此错误:

[ERROR] TypeError: list indices must be integers or slices, not str
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 7, in lambda_handler
    bucket_name = event["Records"]["s3"]["bucket"]["name"]

标签: pythonamazon-web-servicesamazon-s3aws-lambdaboto3

解决方案


推荐阅读