树莓派Pico W使用micropython-firebase-firestore写入数据报错求助
树莓派Pico W + micropython-firebase-firestore 写入Firestore失败排查方案
核心问题定位
你的代码中FirebaseJson字段路径缺少fields/前缀,导致生成的请求体不符合Firestore REST API格式要求,最终触发urequests.py的AssertionError。此外,firestore.patch的参数使用也需要调整。
修复步骤
1. 修正FirebaseJson的字段路径
Firestore的文档结构要求所有字段必须嵌套在fields对象下,构造doc2时需要在字段路径前添加fields/前缀:
doc2 = FirebaseJson() # 正确路径格式:fields/[字段名]/[值类型] doc2.set("fields/value1/stringValue", "Hello World!")
2. 调整firestore.patch参数
update_mask参数为可选,若已通过doc2指定更新字段,可省略该参数;同时建议将merge设为True,确保合并现有文档而非替换:
# 省略update_mask,自动识别更新字段 response = firestore.patch("collection1/document1", doc2, merge=True)
若需指定更新掩码,需确保列表中的字段名与doc2中的字段一致:
response = firestore.patch("collection1/document1", doc2, ["value1"], merge=True)
3. 验证请求体格式
在发送请求前打印doc2的原始数据,确认格式符合要求:
print(doc2.to_raw()) # 预期输出:{"fields": {"value1": {"stringValue": "Hello World!"}}}
4. 检查Firestore安全规则
确保Firestore安全规则允许认证用户写入数据,示例规则:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth != null; } } }
修改后的完整代码片段
#============================修复后代码============================================ doc2 = FirebaseJson() doc2.set("fields/value1/stringValue", "Hello World!") print("验证请求体格式:", doc2.to_raw()) response = firestore.patch("collection1/document1", doc2, merge=True) print("更新成功!响应:", response) #============================修复后代码============================================
额外排查点
- 打印
auth.session.access_token确认令牌有效 - 确保Pico W网络连接稳定,避免请求超时
- 检查
ufirestore库版本,优先使用最新版本修复已知bug
内容的提问来源于stack exchange,提问作者İbrahim Yeşil
相关产品推荐
相关产品推荐

