使用Python向Firestore添加数据遇504超时及方法提示问题
Firestore Python SDK 问题修复指南
一、VSCode自动补全不显示.set()方法
这大概率是类型提示未生效导致的,按以下步骤解决:
- 添加类型注解:给
db变量明确类型,让VSCode能识别它的方法。把db = firestore.client()改成db: firestore.Client = firestore.client(),语言服务就能正确解析.set()这类方法了。 - 更新依赖包:旧版本的
firebase-admin或google-cloud-firestore可能缺失类型定义,执行pip install --upgrade firebase-admin google-cloud-firestore更新到最新版。 - 检查VSCode配置:在设置里开启基础类型检查,把
python.analysis.typeCheckingMode设为basic,确保类型提示功能正常工作。
二、504 Deadline Exceeded 错误
这个超时错误和权限关系不大,主要是网络或请求设置问题,试试这些方案:
- 延长请求超时:调用
.set()时加上timeout参数,比如db.collection("cities").document("LA").set(data, timeout=60),把超时时间从默认的几秒延长到60秒,给网络请求足够时间。 - 排查网络环境:确认本地网络能正常访问Firestore,试试切换网络(比如从公司内网换手机热点),或者检查防火墙、代理是否拦截了Firestore的请求。
- 优化数据处理:
uploaded_at字段别转成字符串,直接用datetime.now(timezone.utc),Firestore原生支持datetime类型,减少不必要的序列化操作。如果是批量写入,拆分成多个小请求,避免单次请求负载过大。 - 检查Firestore状态:登录Firebase控制台,确认你的数据库没有处于维护状态或资源超限,这些情况也会导致超时。
修正后的示例代码
from datetime import datetime, timezone import firebase_admin from firebase_admin import credentials, firestore from google.api_core.exceptions import GoogleAPICallError cred = credentials.Certificate("code/firebase.json") firebase_admin.initialize_app(cred) # 明确类型注解,提升VSCode补全能力 db: firestore.Client = firestore.client() try: test_data = { "session_id": "test-session", "filename": "test.pdf", "url": "https://example.com/test.pdf", "uploaded_at": datetime.now(timezone.utc) # 用原生datetime类型 } data = {"name": "Los Angeles", "state": "CA", "country": "USA"} # 延长超时时间至60秒 db.collection("cities").document("LA").set(data, timeout=60) # 将test_data写入目标集合(替换成你的集合名) db.collection("uploads").document().set(test_data, timeout=60) print("Data uploaded successfully!") except GoogleAPICallError as e: print(f"Firestore error: {e}")
内容的提问来源于stack exchange,提问作者november
相关产品推荐
相关产品推荐

