You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串提取Python数据?Lambda函数JSON解析问题

解决Lambda函数无法解析API Gateway传递的JSON数据问题

核心问题分析

你当前的问题是:API Gateway传递给Lambda的event['body']是JSON格式的字符串,而非直接的字典对象,所以直接用event.get('name')无法提取字段。另外,你当前的SQL字符串拼接方式存在严重的SQL注入风险,必须修正。

修复步骤

1. 解析JSON格式的请求体

首先需要把event['body']字符串解析成Python字典,才能提取其中的字段:

import json

# 在函数内添加解析逻辑
if event.get('body'):
    try:
        body = json.loads(event['body'])
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'headers': {"Access-Control-Allow-Origin": "*"},
            'body': json.dumps({'error': 'Invalid JSON format'})
        }
else:
    return {
        'statusCode': 400,
        'headers': {"Access-Control-Allow-Origin": "*"},
        'body': json.dumps({'error': 'Missing request body'})
    }

2. 使用参数化查询避免SQL注入

绝对不要用字符串拼接构造SQL语句,这会引发SQL注入漏洞。psycopg2支持参数化查询,用%s作为占位符:

# 替换原SQL拼接代码
postgres_insert_query = "INSERT INTO clients (name, phone, contact) VALUES (%s, %s, %s)"
# 传递参数元组
cursor.execute(postgres_insert_query, (body.get('name'), body.get('phone'), body.get('contact')))

3. 完善异常处理与资源释放

添加数据库操作的异常捕获,确保游标和连接能正确关闭:

import re
import psycopg2
import os
import json

def lambda_handler(event, context):
    password = os.environ['DB_SECRET']
    host = os.environ['HOST']
    connection = None
    cursor = None
    
    try:
        # 解析请求体
        if not event.get('body'):
            return {
                'statusCode': 400,
                'headers': {"Access-Control-Allow-Origin": "*"},
                'body': json.dumps({'error': '请求体不能为空'})
            }
        try:
            body = json.loads(event['body'])
        except json.JSONDecodeError:
            return {
                'statusCode': 400,
                'headers': {"Access-Control-Allow-Origin": "*"},
                'body': json.dumps({'error': 'JSON格式无效'})
            }
        
        # 连接数据库
        connection = psycopg2.connect(
            user="postgres",
            password=password,
            host=host,
            port="5432",
            database="postgres"
        )
        cursor = connection.cursor()
        
        # 参数化插入
        postgres_insert_query = "INSERT INTO clients (name, phone, contact) VALUES (%s, %s, %s)"
        cursor.execute(postgres_insert_query, (body.get('name'), body.get('phone'), body.get('contact')))
        connection.commit()
        
        return {
            'statusCode': 200,
            'headers': {"Access-Control-Allow-Origin": "*"},
            'body': json.dumps({'message': f'成功插入{cursor.rowcount}条数据'})
        }
    except psycopg2.Error as e:
        if connection:
            connection.rollback()
        return {
            'statusCode': 500,
            'headers': {"Access-Control-Allow-Origin": "*"},
            'body': json.dumps({'error': f'数据库操作失败: {str(e)}'})
        }
    finally:
        # 关闭资源
        if cursor:
            cursor.close()
        if connection:
            connection.close()

额外说明

  • API Gateway传递的event结构中,POST请求的JSON数据会被封装在body字段里,且是字符串类型,必须手动解析。
  • 参数化查询不仅能避免SQL注入,还能自动处理字符串转义等问题,安全可靠。
  • 添加异常处理后,能返回更清晰的错误信息,便于调试。

内容的提问来源于stack exchange,提问作者user11631308

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:45:33