在Python中使用多个Firebase应用程序,可以通过Firebase Admin SDK和多个配置文件实现。下面是一种实现方法:
pip install firebase-admin
import firebase_admin
from firebase_admin import credentials
import json
config1 = {
"type": "service_account",
"project_id": "your_project_id_1",
"private_key_id": "your_private_key_id_1",
"private_key": "-----BEGIN PRIVATE KEY-----\nYour Private Key 1\n-----END PRIVATE KEY-----\n",
"client_email": "your_client_email_1",
"client_id": "your_client_id_1",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your_project_id_1%40your_appspot_domain_name.iam.gserviceaccount.com"
}
config2 = {
"type": "service_account",
"project_id": "your_project_id_2",
"private_key_id": "your_private_key_id_2",
"private_key": "-----BEGIN PRIVATE KEY-----\nYour Private Key 2\n-----END PRIVATE KEY-----\n",
"client_email": "your_client_email_2",
"client_id": "your_client_id_2",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your_project_id_2%40your_appspot_domain_name.iam.gserviceaccount.com"
}
with open('config1.json', 'w') as file:
json.dump(config1, file)
with open('config2.json', 'w') as file:
json.dump(config2, file)
请注意,将上述代码中的"your_project_id_1"、"your_private_key_id_1"等替换为实际项目的值。
cred1 = credentials.Certificate('config1.json')
firebase_admin.initialize_app(cred1, name='app1')
cred2 = credentials.Certificate('config2.json')
firebase_admin.initialize_app(cred2, name='app2')
这将初始化两个Firebase应用程序,分别命名为'app1'和'app2'。
from firebase_admin import firestore
# 使用'app1'应用程序
db1 = firestore.client(app='app1')
# 使用'app2'应用程序
db2 = firestore.client(app='app2')
# 对'app1'应用程序进行读写操作
doc_ref1 = db1.collection('users').document('user1')
doc_ref1.set({
'name': 'John',
'age': 30
})
# 对'app2'应用程序进行读写操作
doc_ref2 = db2.collection('users').document('user2')
doc_ref2.set({
'name': 'Jane',
'age': 25
})
通过以上步骤,您可以在Python中使用多个Firebase应用程序,并为每个应用程序创建和管理不同的配置文件。这样可以灵活地与不同的Firebase项目进行交互,适用于需要使用多个Firebase实例的情况。
注意:在使用Firebase时,请确保遵循Firebase的使用规范和政策,以及适用的法律和法规。
领取专属 10元无门槛券
手把手带您无忧上云