[英]check if a Firebase App is already initialized in python
I get the following error:我收到以下错误:
ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
How Can I check if the default firebase app is already initialized or not in python?如何检查默认的 firebase 应用程序是否已在 python 中初始化?
The best way is to control your app workflow so the initialization is called only once.最好的方法是控制您的应用程序工作流程,以便仅调用一次初始化。 But of course, indenpotent code is also a good thing, so here is what you can do to avoid that error:但当然,幂等代码也是一件好事,因此您可以采取以下措施来避免该错误:
import firebase_admin
from firebase_admin import credentials
if not firebase_admin._apps:
cred = credentials.Certificate('path/to/serviceAccountKey.json')
default_app = firebase_admin.initialize_app(cred)
Initialize the app in the constructor在构造函数中初始化应用程序
cred = credentials.Certificate('/path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred)
then in your method you call然后在你的方法中你调用
firebase_admin.get_app()
https://firebase.google.com/docs/reference/admin/python/firebase_admin https://firebase.google.com/docs/reference/admin/python/firebase_admin
I've found the following to work for me.我发现以下内容对我有用。
For the default app:对于默认应用程序:
import firebase_admin
from firebase_admin import credentials
if firebase_admin._DEFAULT_APP_NAME in firebase_admin._apps:
# do something.
I have been using it in this way with a named app:我一直在以这种方式将它与一个命名的应用程序一起使用:
import firebase_admin
from firebase_admin import credentials
if 'my_app_name' not in firebase_admin._apps:
cred = credentials.Certificate('path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://{}.firebaseio.com'.format(project_id),
'storageBucket': '{}.appspot.com'.format(project_id)}, name='my_app_name')
I use this try / except block to handle initialisation of the app我使用这个 try / except 块来处理应用程序的初始化
try:
app = firebase_admin.get_app()
except ValueError as e:
cred = credentials.Certificate(CREDENTIALS_FIREBASE_PATH)
firebase_admin.initialize_app(cred)
You can also use default credentials您还可以使用默认凭据
if (not len(firebase_admin._apps)):
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': "yourprojetid"})
In my case, I faced a similar error.就我而言,我遇到了类似的错误。 But my issue was, I have initialized the app twice in my python file.但我的问题是,我已经在我的 python 文件中初始化了两次应用程序。 So it crashed my whole python file and returns a所以它崩溃了我的整个 python 文件并返回一个ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
I solved this by removing one of my firebase app initialization.我通过删除我的 firebase 应用程序初始化之一解决了这个问题。 I hope this will help someone!!我希望这会帮助某人!!
If you ended up here due to building Cloud Functions in GCP with Python that interacts with Firestore, then this is what worked for me:如果您最终是因为使用与 Firestore 交互的 Python 在 GCP 中构建 Cloud Functions 而来到这里,那么这对我有用:
The reason for using an exception for control flow here is that the firebase_admin._apps is a protected member of the module, so accessing it directly is not best practice either.这里使用控制流异常的原因是firebase_admin._apps是模块的受保护成员,因此直接访问它也不是最佳实践。
import firebase_admin
from firebase_admin import credentials, firestore
def init_with_service_account(file_path):
"""
Initialize the Firestore DB client using a service account
:param file_path: path to service account
:return: firestore
"""
cred = credentials.Certificate(file_path)
try:
firebase_admin.get_app()
except ValueError:
firebase_admin.initialize_app(cred)
return firestore.client()
def init_with_project_id(project_id):
"""
Initialize the Firestore DB client using a GCP project ID
:param project_id: The GCP project ID
:return: firestore
"""
cred = credentials.ApplicationDefault()
try:
firebase_admin.get_app()
except ValueError:
firebase_admin.initialize_app(cred)
return firestore.client()
Reinitializing more than one app in firebase using python :使用 python 在 firebase 中重新初始化多个应用程序:
You need to give different name for different app您需要为不同的应用程序提供不同的名称
For every app we will be generating one object store those objects in list and access those object one by one later对于每个应用程序,我们将生成一个对象,将这些对象存储在列表中,并在以后一一访问这些对象
def getprojectid(proj_url):
p = r'//(.*)\.firebaseio'
x = re.findall(p, url)
return x[0]
objects = []
count = 0
details = dict()
def addtofirebase(json_path, url):
global objects, count, details
my_app_name = getprojectid(url) # Function which returns project ID
if my_app_name not in firebase_admin._apps:
cred = credentials.Certificate(json_path)
obj = firebase_admin.initialize_app(cred,xyz , name=my_app_name) # create the object
objects.append(obj) # Store Initialized Objects in one list
details[my_app_name] = count # Storing index of object in dictionary to access it later using project id
count += 1
ref = db.reference('/',app= objects[details[my_app_name]) # using this reference, change database
else:
ref = db.reference('/',app= objects[details[my_app_name]) # from next time it will get update here. it will not get initialise again and again
You can use你可以使用
firebase_admin.delete_app(firebase_admin.get_app())
And execute the code again并再次执行代码
Make the the app global, don't put the initialize_app() inside the function because whenever the function called it also calls the initialize_app() again.使应用程序全局化,不要将 initialize_app() 放在 function 中,因为每当 function 调用它时,它也会再次调用 initialize_app()。
CRED = credentials.Certificate('path/to/serviceAccountKey.json')
DEFAULT_APP = firebase_admin.initialize_app(cred)
def function():
"""call default_app and process data here"""
Use don't need key.json file.使用不需要 key.json 文件。 You can default gcloud credentials to authenticate.您可以使用默认 gcloud 凭据进行身份验证。
gcloud auth application-default login --project="yourproject"
python code: import firebase_admin python 代码:import firebase_admin
app_options = {'projectId': 'yourproject'}
default_app = firebase_admin.initialize_app(options=app_options)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.