我想使用pycurl来拥有TTFB和TTLB,但是无法在AWS lambda中调用pycurl。
为了关注这个问题,假设我将这个简单的lambda函数称为:
import json
import pycurl
import certifi
def lambda_handler(event, context):
client_curl = pycurl.Curl()
client_curl.setopt(pycurl.CAINFO, certifi.where())
client_curl.setopt(pycurl.URL, "https://www.arolla.fr/blog/author/edouard-gomez-vaez/") #set url
client_curl.setopt(pycurl.FOLLOWLOCATION, 1)
client_curl.setopt(pycurl.WRITEFUNCTION, lambda x: None)
content = client_curl.perform()
dns_time = client_curl.getinfo(pycurl.NAMELOOKUP_TIME) #DNS time
conn_time = client_curl.getinfo(pycurl.CONNECT_TIME) #TCP/IP 3-way handshaking time
starttransfer_time = client_curl.getinfo(pycurl.STARTTRANSFER_TIME) #time-to-first-byte time
total_time = client_curl.getinfo(pycurl.TOTAL_TIME) #last requst time
client_curl.close()
data = json.dumps({'dns_time':dns_time,
'conn_time':conn_time,
'starttransfer_time':starttransfer_time,
'total_time':total_time,
})
return {
'statusCode': 200,
'body': data
}我有以下错误,这是可以理解的:
Unable to import module 'lambda_function': No module named 'pycurl'为了创建一个层,我遵循了tuto https://aws.amazon.com/fr/premiumsupport/knowledge-center/lambda-layer-simulated-docker/,但是在生成带有docker的层时有以下错误(我提取了有趣的部分):
Could not run curl-config: [Errno 2] No such file or directory: 'curl-config': 'curl-config'我甚至尝试在我自己的机器上生成这个层:
pip install -r requirements.txt -t python/lib/python3.6/site-packages/
zip -r mypythonlibs.zip python > /dev/null然后将zip上传为aws中的一个层,但是当我登陆lambda时又出现了另一个错误:
Unable to import module 'lambda_function': libssl.so.1.0.0: cannot open shared object file: No such file or directory似乎该层必须建立在某种扩展的目标环境上。
发布于 2021-05-28 17:15:10
经过几个小时的挠头,我设法解决了这个问题。
TL;DR:通过使用从aws继承的坞映像构建层,但是使用所需的库,例如libcurl-devel、openssl-devel、python36-devel。注意3 :)。
详细的方法:
pycurl的requirements.txt (在我的示例中是:--这个目录),创建以下Dockerfile ( create 3):FROM public.ecr.aws/sam/build-python3.6
RUN yum install libcurl-devel python36-devel -y
RUN yum install openssl-devel -y
ENV PYCURL_SSL_LIBRARY=openssl
RUN ln -s /usr/include /var/lang/includedocker build -t build-python3.6-pycurl .,使用此映像(cf 2)构建层
docker run -v "$PWD":/var/task "build-python3.6-pycurl" /bin/sh -c "pip install -r requirements.txt -t python/lib/python3.6/site-packages/; exit"zip mylayer.zip python > /dev/nullhttps://aws.amazon.com/fr/premiumsupport/knowledge-center/lambda-layer-simulated-docker/).
mylayer.zip作为一个层发送到aws,并使您的lambda指向它(使用控制台或遵循tuto
注1.如果您想使用python 3.8,只需将3.6或36改为3.8和38。
注意2.在重新生成层时不要忘记删除python文件夹,必要时使用管理权限。
注意DockerFile最后一行中的符号链接。没有它,gcc将无法找到一些头文件,例如Python.h。
注4.用pycurl后端编译openssl,因为它是lambda执行环境中使用的ssl后端。否则,在执行lambda时将得到一个libcurl link-time ssl backend (openssl) is different from compile-time ssl backend错误。
https://stackoverflow.com/questions/67729764
复制相似问题