> 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> 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文件(因为它更快)。为此,我将在虚拟环境上安装所有外部软件包,以便我可以在本地使用它们进行开发和调试。
>
[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}
将图层添加到堆栈中
我们现在需要在lambdas template.yml上设置图层。我们需要在资源中添加以下以下内容:部分(根据您的项目调整内容)
> ./ lambdas/mylambda/template.yml>
└── 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>现在我们可以调用它。我创建了一个事件文件来测试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。
layers/ └── layer_utils/ └── python/ ├── layer_utils/ │ ├── __init__.py │ └── request_handler.py │ └── processor.py
设置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环境,它需要使用环境文件中的环境变量。这就是应该看起来像
>
>最后,我们需要修改我们的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中文网其他相关文章!

可以使用多种方法在Python中连接两个列表:1.使用 操作符,简单但在大列表中效率低;2.使用extend方法,效率高但会修改原列表;3.使用 =操作符,兼具效率和可读性;4.使用itertools.chain函数,内存效率高但需额外导入;5.使用列表解析,优雅但可能过于复杂。选择方法应根据代码上下文和需求。

有多种方法可以合并Python列表:1.使用 操作符,简单但对大列表不内存高效;2.使用extend方法,内存高效但会修改原列表;3.使用itertools.chain,适用于大数据集;4.使用*操作符,一行代码合并小到中型列表;5.使用numpy.concatenate,适用于大数据集和性能要求高的场景;6.使用append方法,适用于小列表但效率低。选择方法时需考虑列表大小和应用场景。

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python中,for循环用于遍历可迭代对象,while循环用于条件满足时重复执行操作。1)for循环示例:遍历列表并打印元素。2)while循环示例:猜数字游戏,直到猜对为止。掌握循环原理和优化技巧可提高代码效率和可靠性。

要将列表连接成字符串,Python中使用join()方法是最佳选择。1)使用join()方法将列表元素连接成字符串,如''.join(my_list)。2)对于包含数字的列表,先用map(str,numbers)转换为字符串再连接。3)可以使用生成器表达式进行复杂格式化,如','.join(f'({fruit})'forfruitinfruits)。4)处理混合数据类型时,使用map(str,mixed_list)确保所有元素可转换为字符串。5)对于大型列表,使用''.join(large_li

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3汉化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版