环境安装
pip install firebase-admin
编写代码
# coding=utf-8
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from google.cloud.firestore_v1 import FieldFilter
# 初始化Firebase SDK
file_path = 'your api key'
cred = credentials.Certificate(file_path)
firebase_admin.initialize_app(cred)
# 获取Firestore客户端
db = firestore.client()
# 添加文档
def add_document(collection_id, document_data):
doc_ref = db.collection(collection_id).document()
doc_ref.set(document_data)
print('文档已添加!')
# 更新文档
def update_document(collection_id, document_id, update_data):
doc_ref = db.collection(collection_id).document(document_id)
doc_ref.update(update_data)
print('文档已更新!')
# 获取文档
def get_document(collection_id, document_id):
doc_ref = db.collection(collection_id).document(document_id)
document = doc_ref.get()
if document.exists:
print('文档数据:{}'.format(document.to_dict()))
else:
print('文档不存在!')
# 删除文档
def delete_document(collection_id, document_id):
doc_ref = db.collection(collection_id).document(document_id)
doc_ref.delete()
print('文档已删除!')
# 条件查询
def get_document_id(collection_id, field, value):
documents = db.collection(collection_id).where(filter=FieldFilter(field, "==", value)).stream()
docs = [doc.id for doc in documents]
return docs
def change_expire_time(value):
collection_id = 'trans_active'
field = 'number'
update_data = {'expiredAt': 0}
doc1 = get_document_id(collection_id, field, value)[0]
update_document(collection_id, doc1, update_data)
def delete_opt_record(value):
collection_id = 'opt_cmd'
field1 = 'reqNumber'
field2 = 'userNumber'
doc1 = get_document_id(collection_id, field1, value)
doc2 = get_document_id(collection_id, field2, value)
[delete_document(collection_id, d1) for d1 in doc1]
[delete_document(collection_id, d2) for d2 in doc2]
def get_number_provider(value):
collection_id = 'trans_active'
field = 'number'
documents = db.collection(collection_id).where(filter=FieldFilter(field, "==", value)).stream()
provider = [doc.to_dict().get('provider') for doc in documents]
return provider[0]
if __name__ == '__main__':
# value1 = '替换成your number'
# change_expire_time(value1)
# delete_opt_record(value1)
valueList = ['number1', 'number2']
providerList = [get_number_provider(val) for val in valueList]
providers = zip(valueList, providerList)
print(dict(providers))