> aws lambda层是能够与不同的lambdas重复使用代码的好方法。我已经看到了许多有关如何为现有的PIP软件包创建层的教程,但是没有那么多解释如何使用自己的代码来进行操作并允许您与lambda一起进行调试。在我的情况下,您可以使用此层有几层和几个lambdas,并沿模拟AWS环境调试Lambdas和层的代码。我将假设您已经拥有使用其template.yml创建的lambda函数。如果不是,请查看以下文章,以了解如何创建lambda https://docs.aws.amazon.com/lambda/lambda/latest/dg/getting-started.html。创建它后,您可以将其下载为zip文件,然后从那里提取代码和template.yml。
首先,我们需要设置该图层的文件夹结构。我喜欢创建一个称为layers的文件夹,每一层都创建自己的文件夹。 AWS lambda需要该图层的特定文件夹结构,其中每个层的代码位于Python/文件夹中。有关此信息的更多信息,请参见以下链接。 https://docs.aws.amazon.com/lambda/latest/dg/packaging-layers.html
我们的图层将称为layer_utils。然后,我们将一个文件夹layer_utils放入Python文件夹中,内部我们创建文件request_handler.py和processor.py和代码。我们还需要一个init
layers/ └── layer_utils/ └── python/ ├── layer_utils/ │ ├── __init__.py │ └── request_handler.py │ └── processor.py
./ layers/layer_utils/python/layer_utils/processor.py.py
import requests def process_data(url): """ Fetches data from a URL. Args: url (str): The URL to fetch data from. Returns: str: The fetched content or an error message. """ try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text[:200] # Return the first 200 characters of the response except requests.RequestException as e: return f"Error fetching data: {str(e)}"
./ layers/layer_utils/python/layer_utils/request_handler.py
from layer_utils.processor import process_data def handle_request(request): """ Handles an incoming request and processes it. Args: request (dict): The input request data. Returns: dict: The processed result. """ # Example: Extract 'url' from the request and process it if "url" not in request: return {"error": "Missing 'data' in request"} data = request["url"] processed_result = process_data(data) return {"result": processed_result}
包装您的层
这是树的外观
>
PIP将使用Pyproject.toml使用我们的图层来创建软件包。
./ layers/layer_utils/python/python/pyproject.toml
layers/ └── layer_utils/ └── python/ ├── layer_utils/ │ ├── __init__.py │ └── request_handler.py │ └── processor.py
在此文件中,Setuptools软件包对于创建软件包来说是必需的,并且使用车轮软件包将代码包装到可分布的格式中。
> the要求。txt指示我们的图层所需的所有外部模块。在我们的情况下,我们只需要请求模块,但是您可以在必要时添加尽可能多的模块。
./ layers/layer_utils/python/sumpliont.txt
import requests def process_data(url): """ Fetches data from a URL. Args: url (str): The URL to fetch data from. Returns: str: The fetched content or an error message. """ try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text[:200] # Return the first 200 characters of the response except requests.RequestException as e: return f"Error fetching data: {str(e)}"
)。
from layer_utils.processor import process_data def handle_request(request): """ Handles an incoming request and processes it. Args: request (dict): The input request data. Returns: dict: The processed result. """ # Example: Extract 'url' from the request and process it if "url" not in request: return {"error": "Missing 'data' in request"} data = request["url"] processed_result = process_data(data) return {"result": processed_result}
第二个通过调用运行虚拟环境激活脚本的内置命令源来激活虚拟环境。如果您使用的是Visual Studio代码,则可能会提示您切换到虚拟环境。是的。
之后,您应该在外壳中看到类似的东西。
>
└── layer_utils └── python ├── layer_utils │ ├── __init__.py │ ├── processor.py │ └── request_handler.py ├── pyproject.toml └── requirements.txt
有时,我喜欢直接使用SAM工具来调试运行Python文件(因为它更快)。为此,我将在虚拟环境上安装所有外部软件包,以便我可以在本地使用它们进行开发和调试。
>
[project] name = "layer_utils" version = "0.1.0" [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta"
我们现在需要打包该层,因此我们的lambda可以找到该层作为Python软件包。
requests==2.32.2
好吧,现在让我们看看我们将如何调试。这是我的文件夹结构,带有图层和lambdas。
>
layers/ └── layer_utils/ └── python/ ├── layer_utils/ │ ├── __init__.py │ └── request_handler.py │ └── processor.py
这是我的lambda
的代码
import requests def process_data(url): """ Fetches data from a URL. Args: url (str): The URL to fetch data from. Returns: str: The fetched content or an error message. """ try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text[:200] # Return the first 200 characters of the response except requests.RequestException as e: return f"Error fetching data: {str(e)}"
您可以运行文件,并且应该获得没有错误的有效结果。
>如果您使用的是带有Pylance的Visual Studio代码,您可能会发现即使代码有效,该图层的导入也无法解决。
为了解决此问题,您可以编辑工作空间的设置。 DO Control/Command Shift P,输入首选项:打开工作区设置(JSON),并在括号内添加以下内容(如果您有更多的Extroapaths,只需添加路径)
from layer_utils.processor import process_data def handle_request(request): """ Handles an incoming request and processes it. Args: request (dict): The input request data. Returns: dict: The processed result. """ # Example: Extract 'url' from the request and process it if "url" not in request: return {"error": "Missing 'data' in request"} data = request["url"] processed_result = process_data(data) return {"result": processed_result}
将图层添加到堆栈中
>
└── layer_utils └── python ├── layer_utils │ ├── __init__.py │ ├── processor.py │ └── request_handler.py ├── pyproject.toml └── requirements.txt
>的lambda部分上引用该图层。
[project] name = "layer_utils" version = "0.1.0" [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta"
>让我们对此进行测试。让我们先构建它。我从与位置的不同路径构建模板方面遇到了问题,因为在模板中,有关于源代码所在位置的指示。为了避免这种情况,我建议直接从模板文件的路径构建它。
>这将建立所有必要的依赖关系。
requests==2.32.2
./ lambdas/mylambda/events/event.json
>现在我们可以调用调试文件。请记住,您需要为此安装并运行Docker。同样,请记住从模板文件所在的地方调用此。
python3.12 -m venv venv source venv/bin/activate
>这将在template.yml上调用函数。 -d标志表示调试端口为5678。-E标志指示将提交给lambda的事件文件在哪里。
>现在,通过将代码部署到AWS。
layers/ └── layer_utils/ └── python/ ├── layer_utils/ │ ├── __init__.py │ └── request_handler.py │ └── processor.py
设置VSCODE进行调试
我们需要添加调试配置。为此,请执行控制/命令换档P并输入调试:添加配置。...这将打开启动。JSON文件。您需要在此处添加配置。
>我们正在使用将附加到SAM Local Invoke的Debugpy,在这里我们设置了使用-D标志调用时看到的端口5678。确保Localroot指向Lambda代码所在的目录。如果您有更多配置,请将配置中的零件添加到列表中。
import requests def process_data(url): """ Fetches data from a URL. Args: url (str): The URL to fetch data from. Returns: str: The fetched content or an error message. """ try: response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes return response.text[:200] # Return the first 200 characters of the response except requests.RequestException as e: return f"Error fetching data: {str(e)}"
> txt的要求中。
./ lambdas/mylambda/supiends.txt
现在,让我们与PIP
from layer_utils.processor import process_data def handle_request(request): """ Handles an incoming request and processes it. Args: request (dict): The input request data. Returns: dict: The processed result. """ # Example: Extract 'url' from the request and process it if "url" not in request: return {"error": "Missing 'data' in request"} data = request["url"] processed_result = process_data(data) return {"result": processed_result}
>您也可以通过要求安装它。TXT文件
└── layer_utils └── python ├── layer_utils │ ├── __init__.py │ ├── processor.py │ └── request_handler.py ├── pyproject.toml └── requirements.txt
>我们需要创建一个环境文件,在其中我们可以定义一个AWS_SAM_LOCAL环境变量,该变量将告诉我们的图层它在本地运行。我们在工作区文件夹上创建一个文件.ENV。
[project] name = "layer_utils" version = "0.1.0" [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta"
./
>在这里,我们定义AWS_SAM_LOCAL,以便Lambda知道通过AWS SAM在本地运行的Lambda。
>我们还需要告诉我们的Python环境,它需要使用环境文件中的环境变量。这就是应该看起来像
>
>最后,我们需要修改我们的lambda代码,以便知道在本地运行时需要将其附加到调试器。在文件的开始,我们将添加以下代码
python3.12 -m venv venv source venv/bin/activate
现在,我们调用函数(再次,从函数的路径中):
>
(venv) usar@MacBookPro my-lambda-project
调试时
pip3 install -r ./layers/layer_utils/python/requirements.txt
>现在您准备好调试本地层和lambdas!
>以上是创建,调试和部署您的代码作为可重复使用的AWS lambda层的详细内容。更多信息请关注PHP中文网其他相关文章!