使用Python关闭AWS Lambda执行上下文后进行清理 [英] Cleaning up after AWS Lambda execution context is closed with Python
问题描述
利用执行上下文重用来改善函数的性能.在函数处理程序之外初始化SDK客户端和数据库连接,[...]
Take advantage of execution context reuse to improve the performance of your function. Initialize SDK clients and database connections outside of the function handler, [...]
我想实现此原则来改进我的lambda函数,该函数在每次调用该函数时都会初始化并关闭数据库句柄.请看以下示例:
I would like to implement this principle to improve my lambda function, where a database handle is initialized and closed every time the function is invocated. Take the following example:
def lambda_handler(event, context):
# Open a connection to the database
db_handle = connect_database()
# Do something with the database
result = perform_actions(db_handle)
# Clean up, close the connection
db_handle.close()
# Return the result
return result
根据我对AWS文档的理解,应按以下方式优化代码:
From my understanding of the AWS documentation, the code should be optimized as follows:
# Initialize the database connection outside the handler
db_handle = conn_database()
def lambda_handler(event, context):
# Do something with the database and return the result
return perform_actions(db_handle)
这将导致未调用 db_handle.close()
方法,从而可能导致连接泄漏.
This would result in the db_handle.close()
method not being called, thus potentially leaking a connection.
将AWS Lambda与Python结合使用时,应如何处理此类资源的清理工作?
How should I handle the cleanup of such resources when using AWS Lambda with Python?
推荐答案
许多人都在寻找与您相同的东西.我相信这是不可能的.但是我们可以从数据库方面解决问题.
Many people looking for the same thing with you. I believe it is impossible at this time. But we could handle the issue from the database side.
看看 查看全文