| import firebase_admin | |
| from firebase_admin import credentials, firestore | |
| import os | |
| import json | |
| db = None | |
| def init_db(): | |
| global db | |
| if not firebase_admin._apps: | |
| config = os.getenv("FIREBASE_CONFIG") | |
| json_path = "serviceAccountKey.json" | |
| try: | |
| if config: | |
| cred = credentials.Certificate(json.loads(config)) | |
| firebase_admin.initialize_app(cred) | |
| db = firestore.client() | |
| elif os.path.exists(json_path): | |
| cred = credentials.Certificate(json_path) | |
| firebase_admin.initialize_app(cred) | |
| db = firestore.client() | |
| except Exception as e: | |
| print(f"DB Error: {e}") | |
| else: | |
| db = firestore.client() | |
| init_db() | |