Python Azure Functions嵌套代码无法找到模块求助(已加__init__.py)
解决Azure Functions中嵌套结构模块找不到问题
问题背景
将代码从扁平结构重构为嵌套结构后,在Python 3.12.8的Azure Functions中遇到模块找不到的问题。已添加所有__init__.py文件,尝试多种sys.path配置无效,但本地test.py运行正常,推测问题出在Azure Functions的启动机制上。
环境信息
- Python版本:3.12.8
- Azure Functions Core Tools版本:4.0.6821
- Function Runtime Version:4.1036.1.23224
代码片段
本地运行正常的test.py
import sys from pathlib import Path # 获取当前文件(test_function.py)的目录 current_dir = Path(__file__).parent # 将'code'目录添加到PYTHONPATH sys.path.append(str(current_dir / 'code')) try: from code.db.database import SessionLocal print("Import successful: SessionLocal is available.") except ModuleNotFoundError as e: print(f"Import failed: {e}")
出现问题的function_app.py
import os import azure.functions as func from pathlib import Path import logging import json from datetime import datetime import sys # 添加父目录到Python路径 import sys from pathlib import Path # 获取当前文件(function_app.py)的目录 current_dir = Path(__file__).parent # ✅ 语法正确 sys.path.append(os.path.join(os.path.dirname(__file__), 'code')) # 导航到项目根目录(根据你的结构调整) project_root = current_dir.parent # 假设KUSA是kusa.marketing的父目录 sys.path.insert(0, str(project_root)) # 导入模块 from code.db.database import SessionLocal from code.db.database import SessionLocal # 改为相对导入 from generate_jobber_auth import generate_jobber_auth_url, handle_jobber_callback from JobberSyncManager import JobberSyncManager from jobber_auth_models import JobberToken app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION) @app.route(route="buildcompanyprofile", auth_level=func.AuthLevel.ANONYMOUS) def buildcompanyprofile(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.')
报错信息
Exception: ModuleNotFoundError: No module named 'code.db'; 'code' is not a package. Cannot find module. Please check the requirements.txt file for the missing module. Current sys.path: ['C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64', 'C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64', 'C:\Users\Steve\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Steve\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Steve\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Steve\AppData\Local\Programs\Python\Python312', 'C:\Users\Steve\Documents\GitHub\KUSA\kusa.marketing\.venv', 'C:\Users\Steve\Documents\GitHub\KUSA\kusa.marketing\.venv\Lib\site-packages', 'C:\Users\Steve\Documents\GitHub\KUSA\kusa.marketing'] Stack: File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 469, in _handle__functions_metadata_request self.load_function_metadata( File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 449, in load_function_metadata self.index_functions(function_path, function_app_directory)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 822, in index_functions indexed_functions = loader.index_function_app(function_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\utils\wrappers.py", line 49, in call raise extend_exception_message(e, message) File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\utils\wrappers.py", line 44, in call return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Steve\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\3.12\WINDOWS\X64\azure_functions_worker\loader.py", line 244, in index_function_app imported_module = importlib.import_module(module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Steve\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Steve\Documents\GitHub\KUSA\kusa.marketing\function_app.py", line 21, in from code.db.database import SessionLocal
解决方案建议
- 修正sys.path配置逻辑:当前代码同时添加了
code目录和项目根目录到sys.path,导致Python识别code时混淆。应只添加项目根目录到sys.path,确保code作为根目录下的包被识别:import sys from pathlib import Path # 获取function_app.py所在目录 current_dir = Path(__file__).parent # 项目根目录是kusa.marketing的父目录KUSA project_root = current_dir.parent # 将项目根目录插入到sys.path最前面 sys.path.insert(0, str(project_root)) # 此时可正常导入 from code.db.database import SessionLocal - 检查__init__.py文件完整性:确保
code/、code/db/目录下都存在空的__init__.py文件,Python才能将这些目录识别为包。 - 删除重复导入语句:function_app.py中重复写了
from code.db.database import SessionLocal,删除其中一条。 - 验证目录结构:确认项目目录结构如下:
KUSA/ ├── kusa.marketing/ │ ├── function_app.py │ └── code/ │ ├── __init__.py │ └── db/ │ ├── __init__.py │ └── database.py └── ... - 模拟Azure环境测试:本地运行时使用
func start命令启动,而非直接运行function_app.py,两者工作目录可能不同。
内容的提问来源于stack exchange,提问作者Steve Coleman
相关产品推荐
相关产品推荐

