Firebase App이 python에서 이미 초기화되었는지 확인합니다.
다음 오류가 발생합니다.
값 오류:기본 Firebase 앱이 이미 있습니다.즉, 두 번째 인수로 앱 이름을 제공하지 않고 initialize_app()을 두 번 이상 호출한 것입니다.대부분의 경우 initialize_app()을 한 번만 호출하면 됩니다.그러나 여러 앱을 초기화하려면 두 번째 인수를 전달하여 initialize_app()을 입력하여 각 앱에 고유한 이름을 지정합니다.
파이썬에서 기본 파이어베이스 앱이 이미 초기화되었는지 확인하려면 어떻게 해야 합니까?
가장 좋은 방법은 초기화가 한 번만 호출되도록 앱 워크플로우를 제어하는 것입니다.그러나 물론 등치 코드도 좋은 것이므로 이러한 오류를 방지하기 위해 다음과 같이 할 수 있습니다.
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)
생성자에서 앱 초기화
cred = credentials.Certificate('/path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred)
그런 다음 당신이 부르는 방법으로.
firebase_admin.get_app()
https://firebase.google.com/docs/reference/admin/python/firebase_admin
앱 초기화를 처리하기 위해 블록을 제외하고 이 시도를 사용합니다.
try:
app = firebase_admin.get_app()
except ValueError as e:
cred = credentials.Certificate(CREDENTIALS_FIREBASE_PATH)
firebase_admin.initialize_app(cred)
저는 저를 위해 다음과 같은 것들을 찾았습니다.
기본 앱의 경우:
import firebase_admin
from firebase_admin import credentials
if firebase_admin._DEFAULT_APP_NAME in firebase_admin._apps:
# do something.
이름이 지정된 앱을 사용하여 다음과 같은 방식으로 사용해 왔습니다.
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')
Firestore와 상호 작용하는 Python을 사용하여 GCP에서 Cloud Functions를 구축했기 때문에 여기에 오게 된 것이라면 다음과 같습니다.
여기서 제어 흐름에 예외를 사용하는 이유는 firebase_admin 때문입니다._filename은 모듈의 보호 멤버이므로 직접 액세스하는 것도 모범 사례가 아닙니다.
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()
사용할 수 있습니다.
firebase_admin.delete_app(firebase_admin.get_app())
코드를 다시 실행합니다.
기본 자격 증명을 사용할 수도 있습니다.
if (not len(firebase_admin._apps)):
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
'projectId': "yourprojetid"})
저의 경우에도 비슷한 오류가 발생했습니다.하지만 제 문제는 제 파이썬 파일에서 앱을 두 번 초기화했다는 것입니다.그래서 그것은 내 파이썬 파일 전체를 충돌시키고 반환합니다.
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.
파이어베이스 앱 초기화 중 하나를 제거하여 이 문제를 해결했습니다.이것이 누군가에게 도움이 되기를 바랍니다!!
파이썬을 사용하여 파이어베이스에서 둘 이상의 앱을 다시 초기화하는 중:
다른 앱에 다른 이름을 지정해야 합니다.
모든 앱에 대해 하나의 개체를 생성하여 목록에 해당 개체를 저장하고 나중에 하나씩 액세스합니다.
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
앱을 글로벌하게 만들고, 함수가 호출될 때마다 initialize_app()도 다시 호출하기 때문에 함수 내부에 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"""
key.json 파일이 필요하지 않습니다.인증할 기본 gcloud 자격 증명을 설정할 수 있습니다.
gcloud auth application-default login --project="yourproject"
파이썬 코드:
import firebase_admin
app_options = {'projectId': 'yourproject'}
default_app = firebase_admin.initialize_app(options=app_options)
언급URL : https://stackoverflow.com/questions/44293241/check-if-a-firebase-app-is-already-initialized-in-python
'programing' 카테고리의 다른 글
쉼표로 숫자 형식을 지정하는 오라클 SQL 쿼리 (0) | 2023.06.11 |
---|---|
Docker Wordpress tar: 소유권을 uid 33, gid 33으로 변경할 수 없습니다. 작업이 허용되지 않습니다. (0) | 2023.06.11 |
R 프로세스에 사용할 수 있는 메모리 증가(또는 감소) (0) | 2023.06.11 |
명령줄에서 Windows 이벤트 로그 소스를 만드는 방법은 무엇입니까? (0) | 2023.06.11 |
휴대용 분기 예측 힌트 (0) | 2023.06.11 |