Python+AWS Lambda执行外部SQL脚本本地无效果及打包部署疑问
问题描述
我尝试用Python 3.10 + aws-psycopg2库创建AWS Lambda函数,运行包含CREATE TABLE语法和预定义PL/pgSQL函数的外部SQL脚本,连接AWS PostgreSQL数据库。操作步骤如下:
- 本地工作目录执行依赖安装命令:
pip install aws-psycopg2 -t .
- 编写处理函数代码:
import psycopg2 from psycopg2.extras import RealDictCursor import json # 数据库配置信息 endpoint_db = 'pgdatabase.xxx.amazonaws.com' database_db = 'postgres' username_db = 'postgres' password_db = 'xxxxxx' port_db = 5432 connection = psycopg2.connect( dbname=database_db, user=username_db, password=password_db, host=endpoint_db, port=port_db ) def lambda_handler(): cursor = connection.cursor(cursor_factory = RealDictCursor) cursor.execute(open("insert_clause.sql", "r").read()) cursor.execute(open("update_table.sql", "r").read()) # rows = cursor.fetchall() # json_result = json.dumps(rows) # print(json_result) # return(json_result) print('Done!') lambda_handler()
- 外部SQL脚本内容:
update_table.sql:
UPDATE public.category SET name = 'Horror and Thriller' WHERE category_id = 11;
insert_clause.sql:
INSERT INTO public.copy_actor (actor_id, first_name, last_name) VALUES (201, 'Paul', 'Newman');
本地运行handler函数后,数据库表没有任何修改,请问需要额外配置吗?另外,如果脚本正常运行,把这些SQL脚本包含在Lambda的上传压缩包里是否足够?
解决方案
1. 本地运行无修改的核心原因
psycopg2默认不会自动提交事务,你执行完cursor.execute()后没有提交事务,所以数据库不会保存这些修改。必须手动添加事务提交操作,同时优化连接管理(避免Lambda环境复用导致的连接问题):
修改后的lambda_handler函数:
def lambda_handler(): connection = None cursor = None try: # 将数据库连接放在函数内部,避免Lambda环境复用导致连接失效 connection = psycopg2.connect( dbname=database_db, user=username_db, password=password_db, host=endpoint_db, port=port_db ) cursor = connection.cursor(cursor_factory = RealDictCursor) cursor.execute(open("insert_clause.sql", "r").read()) cursor.execute(open("update_table.sql", "r").read()) connection.commit() # 提交事务,将修改写入数据库 print('Done!') except Exception as e: if connection: connection.rollback() # 出错时回滚事务,避免脏数据 print(f'Error: {e}') finally: # 确保关闭游标和连接,释放资源 if cursor: cursor.close() if connection: connection.close()
2. Lambda部署的文件打包问题
把SQL脚本(insert_clause.sql、update_table.sql)、Python代码文件,以及本地安装的aws-psycopg2依赖一起打包成zip文件,上传到Lambda是足够的,但需要注意两点:
- 压缩包根目录要直接包含handler文件(比如
lambda_function.py)和SQL脚本,不要嵌套子文件夹 - 如果本地是Windows/macOS系统,建议用Docker模拟Lambda的Linux环境安装依赖,避免编译环境不兼容导致的运行错误
内容的提问来源于stack exchange,提问作者Andrei Niță
相关产品推荐
相关产品推荐

