我的简易Firebase Python程序为何尝试连接Auth模拟器?
问题重现
错误信息
firebase_admin.exceptions.UnavailableError: Failed to establish a connection: HTTPConnectionPool(host='localhost', port=9099): Max retries exceeded with url: /identitytoolkit.googleapis.com/v1/projects/fir-api-test2-72710/accounts:lookup (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001B28FC6C4F0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
涉事代码
import json import os from dotenv import load_dotenv import firebase_admin from firebase_admin import credentials, firestore, auth # Firestore database db = None if __name__ == "__main__": # FIRESTORE INITIALISATION load_dotenv() firebase_permisisions = json.loads(os.getenv('FIREBASE_CREDS')) cred = credentials.Certificate(firebase_permisisions) firebase_app = firebase_admin.initialize_app(cred) db = firestore.client() print('getting user') # fails here user = auth.get_user('1234') print(user)
问题描述
程序在同事机器上可正常连接生产环境Auth服务,但本地机器强制尝试连接localhost:9099(Auth模拟器端口);启动模拟器后可运行,但读取的是模拟器内的用户数据。已尝试重启机器、重装Firebase Admin SDK,问题仍存在,此前曾在其他Firebase项目中使用过模拟器。
解决思路
清理残留的模拟器环境变量
Firebase Admin SDK会优先读取FIREBASE_AUTH_EMULATOR_HOST环境变量切换到模拟器模式。检查系统或终端环境中是否存在该变量:- Windows:打开命令提示符,执行
echo %FIREBASE_AUTH_EMULATOR_HOST%,若输出localhost:9099,通过系统属性删除该环境变量。 - macOS/Linux:在终端执行
echo $FIREBASE_AUTH_EMULATOR_HOST,若有值,可在当前终端执行unset FIREBASE_AUTH_EMULATOR_HOST临时清除,或修改~/.bashrc/~/.zshrc移除相关配置。
- Windows:打开命令提示符,执行
检查本地Firebase CLI配置文件
若本地初始化过Firebase项目,根目录下的.firebaserc或firebase.json可能包含模拟器配置。打开这些文件,确认是否有强制启用Auth模拟器的设置,如有则删除对应配置项。显式强制使用生产环境API
如果上述方法无效,可在代码中显式指定Auth客户端的生产环境端点,绕过模拟器配置:# 初始化Firebase App后,修改Auth客户端的请求地址 auth_client = auth.Client(firebase_app) auth_client._http.request_base_url = 'https://identitytoolkit.googleapis.com/v1' # 使用修改后的客户端获取用户 user = auth_client.get_user('1234')重置终端/IDE的环境上下文
部分IDE或终端会缓存环境变量,即使系统变量已删除,当前会话仍可能保留旧值。关闭所有打开的IDE和终端窗口,重新启动后再运行程序。
内容的提问来源于stack exchange,提问作者Richard

