Python操作Cloud Firestore

环境安装

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值