Firebase Cloud Functions Python模块导入报错:找不到src模块
解决Python Firebase函数导入错误与Manifest版本问题
一、先搞定Firebase Manifest版本报错
这个错误是因为Firebase函数的构建清单缺失必填版本字段,必须先解决:
- 在
python-functions目录下找到或创建functions.yaml,添加version: 1字段,示例:
version: 1 functions: status_endpoint: # 需与src/main.py里的函数名对应 source: src entryPoint: status_endpoint
- 同步
firebase.json的函数配置,确保指向正确的源码目录:
{ "functions": { "source": "src" } }
二、修复Python模块导入问题
结合你的目录结构,调整导入方式适配Firebase执行环境:
目录结构确认
python-functions/ ├── src/ │ ├── api/ │ │ ├── __init__.py │ │ └── main.py │ ├── __init__.py │ └── main.py
推荐方案:用相对导入
修改src/main.py的导入逻辑,避免绝对导入的路径问题,同时注意函数名不要重复:
# src/main.py import firebase_functions as https_fn from .api.main import status @https_fn.on_request(timeout_sec=300) def status_endpoint(req: https_fn.Request) -> https_fn.Response: return status(req)
同时src/api/main.py要补全依赖导入:
# src/api/main.py import firebase_functions as https_fn def status(req: https_fn.Request): return https_fn.Response("Hello", status=200)
备选方案:手动添加Python路径
如果一定要用绝对导入,在src/main.py开头加入路径配置:
# src/main.py import sys from pathlib import Path import firebase_functions as https_fn # 把项目根目录加入Python搜索路径 sys.path.append(str(Path(__file__).parent.parent)) import src.api.main as api @https_fn.on_request(timeout_sec=300) def status(req: https_fn.Request) -> https_fn.Response: return api.status(req)
这种方式不够简洁,仅作为临时方案使用。
三、测试与部署
- 本地测试:运行
firebase emulators:start --only functions,确认没有报错。 - 正式部署:执行
firebase deploy --only functions完成上线。
内容的提问来源于stack exchange,提问作者Belen
相关产品推荐
相关产品推荐

