【发布时间】:2020-07-28 09:34:44
【问题描述】:
这是一个后续问题: This Question
我正在尝试使用无服务器框架将一些共享 Python 代码作为 lambda 层上传到 AWS Lambda。
我遵循了@msc 的解决方案(做了一些修改):
项目一:
第 1 步:创建具有以下结构的无服务器项目:
./
└ serverless.yml
└ common/
└ python/
└ Other packages as per requirements.txt
└ my_shared_script.py - my own package
第 2 步:设置我的 .yml 文件:
service: library
provider:
name: aws
runtime: python3.7
stage: dev
region: ap-northeast-1
layers:
Common:
path: common
resources:
Outputs:
CommonLayerExport:
Value:
Ref: CommonLambdaLayer
Export:
Name: CommonLambdaLayer
第 3 步:将我的要求安装到 common/python/ 文件夹中:
requirements.txt:
pandas==1.0.5
安装要求到文件夹:
pip install -r requirements.txt ./common/python/
项目 2
第 1 步:在我的 .yml 文件中引用来自项目 1 的上传层:
functions:
hello:
handler: handler.hello
layers:
- arn:aws:lambda:ap-southeast-1:182739821739:layer:Common:1
第 2 步:所有导入现在都可以使用。来自我的handler.py:
import pandas
import my_shared_script
def hello(event, context):
print(my_shared_script.foo())
函数foo()按预期运行。
我现在的问题是my_shared_script.py 现在与所有已安装的 Python 包位于同一文件夹中(有很多文件和文件夹),这使得我很难找到和维护我自己的模块/脚本。
./
└ serverless.yml
└ common/
└ python/
└ Other packages as per requirements.txt
└ lib/
└ my_shared_script.py - my own package
将我自己的脚本放在一个单独的文件夹 /lib 中并将所有其他要求安装到 /python 文件夹中对我来说是有意义的。
但是,如果我使用上面的文件夹结构,代码会失败。
我已将它放在项目 2 中 handler.py 的顶部,希望脚本能够在 /lib 中找到我的代码。
import os
import sys
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(CWD, "../lib")))
我正在努力理解这个无服务器框架中的 Python 路径/文件夹结构......希望有专家可以分享他们的解决方案,谢谢。
【问题讨论】:
-
你使用
virtualenv和serverless-python-requirements吗?(serverless.com/plugins/serverless-python-requirements)你为什么将你的需求安装到common/python文件夹中? -
我想如果你可以通过将 common.py 放到 common/python 中导入而不弄乱 sys 路径,你可以将所有库 pip 安装到同一个 common/python 文件夹中。现在将其作为图层上传后,我可以在我的函数中引用该图层并导入 common 即可,以及我安装在同一文件夹 common/python 中的任何其他库
-
@yongsheng 我正在努力解决同样的问题。更简洁的方法是使用符号链接。
标签: python serverless-framework