/tmp 目录可写,其他目录只读,因此在用到依赖库时,需要使用本地安装、打包、上传的方式。Python 依赖包通常可以与函数代码一同上传,或上传至层中,然后绑定使用。pip 替换为 pip3 或 pip2。requirements.txt 中配置依赖信息。pip install -r requirements.txt -t . 命令安装依赖包。通过使用 -t 参数,可以指定依赖包的安装目录,在项目代码目录下执行时,可以使用 -t . 安装在当前目录下。pip freeze > requirements.txt 生成当前环境下所有依赖的 requirements.txt 文件。requests 依赖,其中代码文件 index.py 如下所示:# -*- coding: utf8 -*-import requestsdef main_handler(event, context):addr = "www.qq.com"resp = requests.get(addr)print(resp)return resp
pip3 install requests -t . 在项目当前目录安装 requests 依赖。代码文件如下所示:$ pip3 install requests -t .Collecting requestsUsing cached requests-2.25.1-py2.py3-none-any.whl (61 kB)Collecting certifi>=2017.4.17Using cached certifi-2020.12.5-py2.py3-none-any.whl (147 kB)Collecting chardet<5,>=3.0.2Using cached chardet-4.0.0-py2.py3-none-any.whl (178 kB)Collecting idna<3,>=2.5Using cached idna-2.10-py2.py3-none-any.whl (58 kB)Collecting urllib3<1.27,>=1.21.1Using cached urllib3-1.26.4-py2.py3-none-any.whl (153 kB)Installing collected packages: urllib3, idna, chardet, certifi, requestsSuccessfully installed certifi-2020.12.5 chardet-4.0.0 idna-2.10 requests-2.25.1 urllib3-1.26.4$ ls -ltotal 8drwxr-xr-x 3 xxx 111 96 4 29 16:45 bindrwxr-xr-x 7 xxx 111 224 4 29 16:45 certifidrwxr-xr-x 8 xxx 111 256 4 29 16:45 certifi-2020.12.5.dist-infodrwxr-xr-x 44 xxx 111 1408 4 29 16:45 chardetdrwxr-xr-x 9 xxx 111 288 4 29 16:45 chardet-4.0.0.dist-infodrwxr-xr-x 11 xxx 111 352 4 29 16:45 idnadrwxr-xr-x 8 xxx 111 256 4 29 16:45 idna-2.10.dist-info-rw-r--r--@ 1 xxx 111 177 4 29 16:33 index.pydrwxr-xr-x 21 xxx 111 672 4 29 16:45 requestsdrwxr-xr-x 9 xxx 111 288 4 29 16:45 requests-2.25.1.dist-infodrwxr-xr-x 17 xxx 111 544 4 29 16:45 urllib3drwxr-xr-x 10 xxx 111 320 4 29 16:45 urllib3-1.26.4.dist-info
import 方式引入和使用。同时,依赖也可以打包部署为层,并通过在函数创建部署时,与函数绑定,提供复用能力。pycryptodome 依赖。由于编译程序会根据不同 OS 进行操作系统相关的编译操作,在 Windows、Mac 等环境下编译生成的依赖库及动态库等程序,可能无法在云函数的环境中运行。您可通过以下方案尝试解决:文档反馈