如何为Firebase Python云函数附加VS Code调试器?
调试Firebase Python云函数(VS Code + 模拟器)
Firebase模拟器的--inspect-functions参数仅支持Node.js运行时,Python函数需要借助Python生态的调试工具实现附加调试,以下是具体操作步骤:
1. 添加调试依赖
在你的functions/requirements.txt中加入debugpy(Python官方推荐的调试库):
debugpy>=1.6.7 firebase-functions>=1.1.1 # 其他函数依赖
执行pip install -r requirements.txt完成依赖安装。
2. 修改函数代码,开启调试监听
在云函数入口文件(如main.py)的顶部添加调试监听逻辑:
import debugpy # 监听本地5678端口,允许外部连接以适配模拟器环境 debugpy.listen(("0.0.0.0", 5678)) # 可选:如果需要等待调试器附加后再执行函数逻辑,取消下方注释 # debugpy.wait_for_client() # 你的云函数业务代码 import firebase_functions as functions @functions.http.on_request() def hello_world(request): # 在此行设置断点测试 name = request.args.get("name", "World") return f"Hello {name}!"
3. 启动Firebase函数模拟器
直接启动模拟器,无需添加--inspect-functions参数:
firebase emulators:start --only functions
启动后模拟器会加载你的Python函数,此时debugpy已在监听5678端口。
4. 配置VS Code调试器
打开VS Code的.vscode/launch.json,添加Python附加调试配置:
{ "version": "0.2.0", "configurations": [ { "name": "Attach to Firebase Python Functions", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}/functions", "remoteRoot": "/workspace" } ] } ] }
pathMappings用于映射本地代码路径与模拟器内的代码路径(模拟器默认将functions目录挂载到/workspace)。
5. 附加调试器并测试
- 在VS Code中给Python函数设置断点(点击代码行号左侧)。
- 按下F5启动调试器,自动附加到模拟器中的Python函数进程。
- 触发云函数(如访问模拟器提供的函数URL、用curl调用),代码会在断点处暂停,即可进行调试。
内容的提问来源于stack exchange,提问作者Johnny Oshika
相关产品推荐
相关产品推荐

