首页 >后端开发 >Python教程 >创建,调试和部署您的代码作为可重复使用的AWS lambda层

创建,调试和部署您的代码作为可重复使用的AWS lambda层

DDD
DDD原创
2025-01-30 00:23:09197浏览

> 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 .py空文件,Python必须将其识别为包装。这就是树结构应该看起来像

layers/
└── layer_utils/
    └── python/
        ├── layer_utils/
        │   ├── __init__.py
        │   └── request_handler.py
        │   └── processor.py

> request_handler.py将接收带有URL的请求,并致电将使用库请求获取数据并返回数据的处理器。

./ 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}
>在这里,重要的是要注意如何通过从layer_utils.processor导入process_data而不是从processor import import import process_data导入处理器函数。使用绝对路径有助于以后避免导入错误。

包装您的层

好的,现在我们创建了层代码。但是我们还没有完成。我们现在需要使用PIP创建一个可编辑的软件包,因此可以通过Lambda代码使用。我们将遵循PEP 660风格。我们需要创建两个文件:需求.txt和pyproject.toml。在这种情况下,第一个将包括我们所需的所有外部库。第二个是我们需要使用PIP创建一个可编辑软件包的文件,并确保安装所有依赖关系。这允许编辑图层代码而无需不断重新包装(我们需要调试)。

>

这是树的外观

>


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)}"
>我认为重要的是要跟踪您使用的包装的哪个版本,因为您的外部软件包将通过直接从AWS调用AWS lambda层资源来导入您的外部软件包。如果直接通过直接从Python环境运行Lambda而不是使用SAM Local Invoke或Sam Local Start-API来直接在系统上调试,则需要确保使用PIP安装的本地软件包与已部署的本地套件相同层中的包装。我不会解释如何创建外部图层,因为有很多好的教程(例如,此https://www.keyq.cloud/en/blog/creating-an-an-aws-an-aws-lambda-layer-for- Python-Requests-Module

)。

设置虚拟环境

现在,让我们创建一个虚拟环境。这不是必需的,但是建议它隔离依赖关系并确保Python环境与Lambda将使用的环境一致。为此,在您的项目dir的控制台中,输入


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}
>第一个使Python使用-M VENV运行VENV模块,并创建一个称为VENV的虚拟环境。

第二个通过调用运行虚拟环境激活脚本的内置命令源来激活虚拟环境。如果您使用的是Visual Studio代码,则可能会提示您切换到虚拟环境。是的。

之后,您应该在外壳中看到类似的东西。

>

└── layer_utils
    └── python
        ├── layer_utils
        │   ├── __init__.py
        │   ├── processor.py
        │   └── request_handler.py
        ├── pyproject.toml
        └── requirements.txt
(VENV)一开始表明您在虚拟环境中。

有时,我喜欢直接使用SAM工具来调试运行Python文件(因为它更快)。为此,我将在虚拟环境上安装所有外部软件包,以便我可以在本地使用它们进行开发和调试。

>


>这仅是在没有SAM工具的情况下直接在本地和直接调试的必要条件,因此,如果您不打算这样做,则可以跳过此步骤。
[project]
name = "layer_utils"
version = "0.1.0"

[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

我们现在需要打包该层,因此我们的lambda可以找到该层作为Python软件包。


-e标志表明这是一个可编辑的软件包。路径指向pyproject.toml文件的位置。运行此功能将创建一个新的文件夹layer_utils.egg-info。在那里没什么事,只剩下它。
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代码,您可能会发现即使代码有效,该图层的导入也无法解决。

Pylance complaining on VSCode 为了解决此问题,您可以编辑工作空间的设置。 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}

将图层添加到堆栈中

我们现在需要在lambdas template.yml上设置图层。我们需要在资源中添加以下以下内容:部分(根据您的项目调整内容)

>

./ lambdas/mylambda/template.yml

>

>在contenturi中,您可以看到它是指图层代码所在的相对路径。查看如何指向Python文件夹,因为AWS SAM系统将在那里寻找Python文件夹。确保运行时与您在虚拟环境和lamnbda中使用的时间匹配。
└── layer_utils
    └── python
        ├── layer_utils
        │   ├── __init__.py
        │   ├── processor.py
        │   └── request_handler.py
        ├── pyproject.toml
        └── requirements.txt
另外,您需要在文件

>的lambda部分上引用该图层。

请注意,在模板文件的“层”部分中,我们还具有已在AWS上的请求层。这将在本地创建该图层,因此SAM知道它需要阅读它。每当您致电AWS部署时,它也会在AWS上部署此层。>
[project]
name = "layer_utils"
version = "0.1.0"

[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
与山姆调试

>让我们对此进行测试。让我们先构建它。我从与位置的不同路径构建模板方面遇到了问题,因为在模板中,有关于源代码所在位置的指示。为了避免这种情况,我建议直接从模板文件的路径构建它。

>


>这将建立所有必要的依赖关系。

requests==2.32.2
>现在我们可以调用它。我创建了一个事件文件来测试lambda

./ lambdas/mylambda/events/event.json


>现在我们可以调用调试文件。请记住,您需要为此安装并运行Docker。同样,请记住从模板文件所在的地方调用此。

>
python3.12 -m venv venv

source venv/bin/activate


>这将在template.yml上调用函数。 -d标志表示调试端口为5678。-E标志指示将提交给lambda的事件文件在哪里。

将您的lambda和图层部署到AWS

>现在,通过将代码部署到AWS。

如果您尚未部署lambda,则可以在第一次使用 - 引导的标志,因为它将在此过程中为您提供帮助。执行此操作后,您可以转到AWS控制台并找到您的层。现在,您可以使用该图层的ARN将图层与其他lambdas一起使用。
layers/
└── layer_utils/
    └── python/
        ├── layer_utils/
        │   ├── __init__.py
        │   └── request_handler.py
        │   └── processor.py

The lambda layer on the AWS Console 设置VSCODE进行调试

如果您想使用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)}"
>我们将需要调试库进行调试。让我们首先将其添加到您的lambda

> 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环境,它需要使用环境文件中的环境变量。这就是应该看起来像

> requests==2.32.2

>

>最后,我们需要修改我们的lambda代码,以便知道在本地运行时需要将其附加到调试器。在文件的开始,我们将添加以下代码

python3.12 -m venv venv

source venv/bin/activate
./ lambdas/mylambda/src/lambda_function.py

>

现在,我们调用函数(再次,从函数的路径中):
>

(venv) usar@MacBookPro my-lambda-project
当控制台显示等待调试器附加...,按F5或选择python调试器:使用linaign.json

调试时

pip3 install -r ./layers/layer_utils/python/requirements.txt

>现在您准备好调试本地层和lambdas!

>

以上是创建,调试和部署您的代码作为可重复使用的AWS lambda层的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn