为什么我的AWS Lambda意外超时?

-1 投票
1 回答
27 浏览
提问于 2025-04-14 15:32

我有一组可以正常工作的Lambda函数,它们用来处理API请求,并且使用了一个层来管理共享的依赖项。

我想在这个层里添加我自己的模块,用于共享一些函数和类,但当我在测试这个层的Lambda时,导入新模块的时候就超时了。

我可以确认文件确实存在,使用listdir()可以看到它们,就在那些之前一直正常工作的包旁边。

这是我模块的简化内容,叫做functions.py:

import json
import pymysql
import boto3

class InvalidInputException(Exception):

class FailedConnectionException(Exception):

class InternalAWSException(Exception):

def cors_response(_status_code:int, _response_body:dict) -> dict :

def get_db_connection() -> pymysql.Connection:

class XOREncryptor:
    

还有一个__init__.py:

from .functions import XOREncryptor
from .functions import InvalidInputException
from .functions import FailedConnectionException
from .functions import InternalAWSException
from .functions import cors_response
from .functions import get_db_connection

这两个文件都在一个叫helper的文件夹里,和其他的包文件夹在python/目录下是并排的。

我的测试Lambda代码如下:

def lambda_handler(event, context):
    import os
    import json
    import ssl
    import helper
    
    layer_contents = os.listdir('/opt/python')
    helper_contents = os.listdir('/opt/python/helper')
    print(layer_contents)
    print(helper_contents)
    return {
        'statusCode': 200,
        'body': ''
    }

在使用网页控制台的内置测试功能时,这段代码会超时。

如果我不写“import helper”这一行,运行同样的代码就完全没问题,也证明了文件确实在我预期的位置。

1 个回答

3

我来回答我自己的问题。原来只是需要比默认的AWS Lambda超时时间3000毫秒多几秒。

问题是因为我刚创建了包文件并立即上传,所以Python没有生成__pycache__这个存放编译代码的文件夹。第一次运行测试函数大约花了5秒钟,但之后的运行就像预期的一样,只需要大约30毫秒。

撰写回答