yoursdvniel commited on
Commit
88d3d66
·
verified ·
1 Parent(s): 1f4be87

Create config.py

Browse files
Files changed (1) hide show
  1. config.py +31 -0
config.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from functools import lru_cache
4
+ from google.cloud import firestore
5
+ from google.oauth2 import service_account
6
+
7
+ @lru_cache(maxsize=1)
8
+ def get_db() -> firestore.Client:
9
+ """
10
+ Creates a Firestore client using one of:
11
+ 1) Emulator (FIRESTORE_EMULATOR_HOST)
12
+ 2) FIREBASE_CREDENTIALS_JSON (stringified service account JSON)
13
+ 3) ADC (GOOGLE_APPLICATION_CREDENTIALS)
14
+ """
15
+ # Prefer explicit project envs; otherwise pull from SA JSON
16
+ proj = os.getenv("GOOGLE_CLOUD_PROJECT") or os.getenv("FIREBASE_PROJECT_ID")
17
+
18
+ # 1) Emulator
19
+ if os.getenv("FIRESTORE_EMULATOR_HOST"):
20
+ return firestore.Client(project=proj or "local-dev")
21
+
22
+ # 2) Service account JSON in env
23
+ creds_env = os.getenv("FIREBASE_CREDENTIALS_JSON")
24
+ if creds_env:
25
+ info = json.loads(creds_env)
26
+ creds = service_account.Credentials.from_service_account_info(info)
27
+ project_id = proj or info.get("project_id") or "unknown-project"
28
+ return firestore.Client(project=project_id, credentials=creds)
29
+
30
+ # 3) ADC fallback
31
+ return firestore.Client(project=proj or None)