Spaces:
Runtime error
Runtime error
File size: 2,366 Bytes
1ffd0a4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import json
import os
import logging
import firebase_admin
from firebase_admin import credentials, firestore_async
logger = logging.getLogger(__name__)
def init_firebase():
"""Initializes the Firebase Admin SDK singleton.
Credential resolution order:
1. FIREBASE_CREDENTIALS_JSON — full service-account JSON as a string
(used on HF Spaces, where no key file can be committed).
2. FIREBASE_CREDENTIALS_PATH — path to a service-account JSON file.
3. Application default credentials (Cloud Run / gcloud).
"""
if not firebase_admin._apps:
cred_json = os.getenv("FIREBASE_CREDENTIALS_JSON", "").strip()
cred_path = os.getenv("FIREBASE_CREDENTIALS_PATH", "serviceAccountKey.json")
try:
if cred_json:
cred = credentials.Certificate(json.loads(cred_json))
firebase_admin.initialize_app(cred)
logger.info("Firebase initialized from FIREBASE_CREDENTIALS_JSON env var.")
elif os.path.exists(cred_path):
cred = credentials.Certificate(cred_path)
firebase_admin.initialize_app(cred)
logger.info(f"Firebase initialized with credentials at {cred_path}")
else:
firebase_admin.initialize_app()
logger.warning(f"Credentials not found at {cred_path}, falling back to default application credentials.")
except Exception as e:
logger.error(f"Failed to initialize Firebase: {e}")
raise
def get_async_db():
"""Returns the asynchronous Firestore client."""
from google.cloud import firestore
import firebase_admin
import os
app = firebase_admin.get_app()
cred = app.credential.get_credential()
db_id = os.getenv("FIRESTORE_DATABASE_ID", "default")
return firestore.AsyncClient(
project=app.project_id,
credentials=cred,
database=db_id
)
def get_db():
"""Returns the synchronous Firestore client."""
from google.cloud import firestore
import firebase_admin
import os
app = firebase_admin.get_app()
cred = app.credential.get_credential()
db_id = os.getenv("FIRESTORE_DATABASE_ID", "default")
return firestore.Client(
project=app.project_id,
credentials=cred,
database=db_id
)
|