【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误

摘要:
问题描述在Azure中创建FunctionApp以运行Python代码。通过高级工具登录日志文件,看到错误消息:ModuleNotFoundError:Nomodulenamed'psycopg2'。故障排除指南:https://aka.ms/functions-modulenotfound完整的错误消息是:2021 11月24日01:55:27.767[信息]执行'功能。HttpTrigger1'2021 11-24T01:55:28.640[信息]WorkerProcess已启动并初始化。2021 11月24日01:55:28.762[错误]执行的函数。HttpTrigger1“结果:FailureException:ModuleNotFoundError:Nomodulenamed'psycopg2”。故障排除指南:https://aka.ms/functions-modulenotfoundStack:File“/azure functions host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py”,第305行,in_handle__函数_load_requestfunc=加载程序。load_ function(文件“/azure functions host/workers/python/3.8/LINUX/X64/azure_functions_worker/utils/wrappers.py”,第42行,incallraiseeextend_exception_message(e,message)文件“/azzure functions host/workers/python.3.8/LINUX64/azzure_fuctions_worker/utils/wrappers.py”,第40行,incellreturnfunc(*args,**kwargs)文件“/azure fuctions host/workers/pythin/3.8/LinUX64/azure_unctions_worker/loader.py“,第85行,inload_ functionmod=导入库。import_module(完整模块名)文件“/usr/local/lib/python3.8/importlib/__init__.py”,第127行,inimport_modulereturn_bootstrap._gcd_Import(name[level:],package,level)文件“/home/site/wwwroot/HttpTrigger1/__init__.py”,第2行,位于importsophog2问题分析中当无法安装模块时,请参阅《疑难解答指南》(https://aka.ms/functions-modulenotfound)逐步进行故障排除非常有帮助。然而,当前的问题不是我们没有尝试安装模块psycopg2,而是我们没有尝试按照函数的要求安装模块。为了更清楚地了解错误消息,SSH直接连接到运行FunctionApp的Linux实例。
问题描述

在Azure中创建Function App(函数应用), 用以运行Python代码(Python Version 3.7)。 通过VS Code创建一个HttpTrigger的Function,其中使用到了psycopg2 模块,以便连接Azure Database for PostgreSQL 数据库

【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误第1张

当通过VS Code发布到Azure后,请求 Function URL 出错。通过高级工具(Kudu:https://<xxxxxxxx>.scm.chinacloudsites.cn/)登录到Logfiles中查看到错误消息为:

【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误第2张

错误消息显示:ModuleNotFoundError: No module named 'psycopg2'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound

完整的错误消息为:

2021-11-24T01:55:27.767 [Information] Executing 'Functions.HttpTrigger1' (Reason='This function was programmatically called via the host APIs.', Id=fb46530a-60db-4d44-b705-e81f805c9743)
2021-11-24T01:55:28.640[Information] Worker process started and initialized.
2021-11-24T01:55:28.762 [Error] Executed 'Functions.HttpTrigger1' (Failed, Id=fb46530a-60db-4d44-b705-e81f805c9743, Duration=1095ms)
Result: Failure
Exception: ModuleNotFoundError: No module named 'psycopg2'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound
Stack:   File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 305, in_handle__function_load_request
    func =loader.load_function(
  File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 42, incall
    raise extend_exception_message(e, message)
  File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 40, incall
    return func(*args, **kwargs)
  File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/loader.py", line 85, inload_function
    mod =importlib.import_module(fullmodname)
  File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, inimport_module
    return_bootstrap._gcd_import(name[level:], package, level)
  File "/home/site/wwwroot/HttpTrigger1/__init__.py", line 2, in <module>import psycopg2
问题分析

当遇见模块无法安装的时候,可以参考 TroubleShooting Guide (https://aka.ms/functions-modulenotfound) 进行逐步排查,还是非常有帮助的。

但是当前问题,并不是没有尝试安装psycopg2这个模块,而是虽然在Function的 requirements.txt 文件中已经添加了psycopg2,但是在安装的过程中出错。为了更明确的知道错误的消息,直接SSH连接到Function App所运行的Linux实例。通过 python -m pip install psycopg2 查看错误信息:

【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误第3张

错误文本:

root@1ac8c89f91a9:~#  python -m pip install psycopg2
Collecting psycopg2
  Downloading psycopg2-2.9.2.tar.gz (380kB)
     |████████████████████████████████| 380 kB 274 kB/s
    ERROR: Command errored out with exit status 1:
     command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zvgqohj2/psycopg2_46223be3606547c5bbdd49a650506
7d8/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zvgqohj2/psycopg2_46223be3606547c5bbdd49a6505067d8/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file
__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exe
c(compile(code, __file__, '"'"'exec'"'"'))'egg_info --egg-base /tmp/pip-pip-egg-info-4y8snj3a
         cwd: /tmp/pip-install-zvgqohj2/psycopg2_46223be3606547c5bbdd49a6505067d8/Complete output (23lines):
    running egg_info
    creating /tmp/pip-pip-egg-info-4y8snj3a/psycopg2.egg-info
    writing /tmp/pip-pip-egg-info-4y8snj3a/psycopg2.egg-info/PKG-INFO
    writing dependency_links to /tmp/pip-pip-egg-info-4y8snj3a/psycopg2.egg-info/dependency_links.txt
    writing top-level names to /tmp/pip-pip-egg-info-4y8snj3a/psycopg2.egg-info/top_level.txt
    writing manifest file '/tmp/pip-pip-egg-info-4y8snj3a/psycopg2.egg-info/SOURCES.txt'
    Error: pg_config executable not found.

    pg_config is required to build psycopg2 fromsource.  Please add the directory
    containing pg_config to the $PATH or specify the full executable path with the
    option:

        python setup.py build_ext --pg-config /path/to/pg_config build ...

    or with the pg_config option in 'setup.cfg'.

    If you prefer to avoid building psycopg2 fromsource, please install the PyPI
    'psycopg2-binary'package instead.

    For further information please check the 'doc/src/install.rst'file (also at
    <https://www.psycopg.org/docs/install.html>).

    ----------------------------------------WARNING: Discarding https://files.pythonhosted.org/packages/33/ed/79434011d773e5ea4c51262f6ebfb86680c2908d7677f31ebccd5aa9f1b3/psycopg2-2.9.2.tar.gz#sha256=a84da9fa8
91848e0270e8e04dcca073bc9046441eeb47069f5c0e36783debbea (from https://pypi.org/simple/psycopg2/) (requires-python:>=3.6). Command errored out with exit status 1: pyt
hon setup.py egg_info Check the logs for full command output.

真正的错误就是 pg_config 是必须的,但是Linux实例上并没有配置。而解决办法就是使用 psycopg2-binary 包代替,接着使用python -m pip install psycopg2-binary 来测试是否可以安装成功。

【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误第4张

验证成功!

所以为了能在 Python Function 中使用 psycopg2 模块,需要在 requirements.txt 文件中,使用psycopg2-binary 代替 psycopg2。 其他的(如代码中的import psycopg2)则无需修改。

【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误第5张

参考资料

在 Azure 中使用 Visual Studio Code 创建 Python 函数https://docs.azure.cn/zh-cn/azure-functions/create-first-function-vs-code-python

Use Python to connect and query data in Azure Database for PostgreSQL - Single Serverhttps://docs.microsoft.com/en-us/azure/postgresql/connect-python#prerequisites

Install psycopg2 using pip install psycopg2-binary in a terminal or command prompt window.

Using psycopg2 in Azure Functions :https://iotespresso.com/using-psycopg2-in-azure-functions/

psycopg2 is not a standalone package. It is built using libpq-dev package, during installation. Now, psycopg2 depends on the host OS to find this library. And Azure Functions don’t have libpq, as the error above clearly indicates.

You may be wondering that we can perhaps simply add libpq-dev to requirements.txt. But that doesn’t work. You will get the error:

No matching distribution found for libpq-dev

Thus, the required solution is to use a package of psycopg2 that doesn’t require libpq. psycopg2-binary is exactly that. I hope this provided a satisfactory explanation.

[End]

免责声明:文章转载自《【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇使用Laravel集成JWT认证开发RestfulApi我心中“用户体验”几大要素的优先级(转)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Linux下boost库的编译、安装详解

下载boost源码 boost下载地址 解压到一个目录 tar -zxvf boost_1_66_0.tar.gz 1、正常编译: 进入boost_1_66_0目录中 cd boost_1_66_0 ./bootstrap.sh --with-libraries=all --with-toolset=gcc --with-liraries:需要编译的库...

Linux(Centos)下安装git步骤详解

1、先去官网下载一个安装包: 2、解压下载好的git安装包,到当前目录。 命令:tar -zxvf git-2.11.0.tar.gz 3、进入解压后的git-2.11.0目录: 4、安装依赖。 执行命令:yum -y install gcc openssl openssl-devel curl curl-devel unzip perl perl-d...

python 字典 拼接SQL语句

def gen_sql(table_name, data):     """   :param table_name: 表名称   :param data: 字典对象 key为字段(要与数据库字段一样), value为插入值   :return: 拼接好的sql语句   """   fields = list()   values = list()   ...

Python 列表、元组、字典及集合操作详解

一、列表 列表是Python中最基本的数据结构,是最常用的Python数据类型,列表的数据项不需要具有相同的类型 列表是一种有序的集合,可以随时添加和删除其中的元素 列表的索引从0开始 1、创建列表 >>> list1 = ['python', 2018, 'python3', 1994] >>> list1 [...

centos_6下的python3和pip的安装

CentOS 6安装python3 1.安装方式是源码包安装,需要用到 gcc,make yum install gcc make 安装python3需要的依赖包有:openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel yum install o...

python 调用接口

这个比较乱,抽口再修改一下。 工作需要调有赞API的接口数据, 返回数据. 进行数据处理 现在两部分比较重要:1 自动获取数据 , 2处理excel的过程. 明白接口的过程.传入参数 https://open.youzan.com/v3/apicenter/doc-api-main/1/2/salesman/youzan.salesman.trades.g...