在 azure 函数中找不到本地模块

local module not found in azure function

我尝试重现 this setup 以将本地模块导入我的代码。

这是我的文件夹结构,类似于之前的 link:

和我的代码:

嘿嘿/init.py

import logging

from shared.helloworld import sayhello # the way I would like to do it -> doesn't work

# from shared import helloworld # as per documentation, but doesn't work
# import shared.helloworld # as per documentation, still doesn't work


import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info(sayhello("from log"))
    return func.HttpResponse(
             sayhello("from http response"),
             status_code=200
        )

shared/helloworld.py

def sayhello(name : str) -> str:
    return "hello world " + name

我已将 shared/__init__.py 留空,因为我已阅读这是一个不错的做法,并且该文件仅用于将此文件夹标记为可导入。

无论我使用什么语法导入我的模块,我总是遇到同样的错误:

Result: Failure Exception: ModuleNotFoundError: No module named 'shared'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 315, in _handle__function_load_request func = loader.load_function( File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 42, in call raise extend_exception_message(e, message) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/utils/wrappers.py", line 40, in call return func(*args, **kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/loader.py", line 85, in load_function mod = importlib.import_module(fullmodname) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/site/wwwroot/hey/__init__.py", line 3, in from shared.helloworld import sayhello

错误消息中 linked 的文档与本地导入无关,我在这里不知所措。 有人知道为什么我的导入不起作用吗?

文档对其进行了更好的解释。参考这里Microsoft Doc

当我使用 terraform 配置我的 az func 时,我的问题是我没有提供这个块:

resource "azurerm_linux_function_app" "auth_func" {
    ...
    application_stack {
      python_version = "3.9"
    }

万一其他人遇到这个问题,这里有一些调查途径:

  • 确保你 python runtime 在 azure 函数中设置
  • __init__.py 来自导入的包是空的或设计用于 azure 函数(无本地引用)
  • requirements.txt 包含您在代码中使用的所有外部模块