Spaces:
Running
Running
Upload firestore_client.py
Browse files- firestore_client.py +41 -0
firestore_client.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import firebase_admin
|
| 4 |
+
from firebase_admin import credentials, firestore
|
| 5 |
+
|
| 6 |
+
COLLECTION_NAME = "CoconutAdvice"
|
| 7 |
+
|
| 8 |
+
FIREBASE_CREDENTIALS_ENV = "FIREBASE_CREDENTIALS"
|
| 9 |
+
|
| 10 |
+
def init_firestore():
|
| 11 |
+
"""Initializes Firestore using a service account JSON provided via an environment variable.
|
| 12 |
+
|
| 13 |
+
The environment variable should contain the full JSON contents of the Firebase service account
|
| 14 |
+
key (the same JSON that would normally be stored in a file like `serviceAccountKey.json`).
|
| 15 |
+
"""
|
| 16 |
+
if not firebase_admin._apps:
|
| 17 |
+
creds_json = os.getenv(FIREBASE_CREDENTIALS_ENV)
|
| 18 |
+
if not creds_json:
|
| 19 |
+
raise EnvironmentError(
|
| 20 |
+
f"Environment variable {FIREBASE_CREDENTIALS_ENV} is required and must contain "
|
| 21 |
+
"Firebase service account JSON."
|
| 22 |
+
)
|
| 23 |
+
try:
|
| 24 |
+
cred_dict = json.loads(creds_json)
|
| 25 |
+
except json.JSONDecodeError as e:
|
| 26 |
+
raise ValueError(
|
| 27 |
+
f"Failed to parse JSON from {FIREBASE_CREDENTIALS_ENV}: {e}"
|
| 28 |
+
) from e
|
| 29 |
+
|
| 30 |
+
cred = credentials.Certificate(cred_dict)
|
| 31 |
+
firebase_admin.initialize_app(cred)
|
| 32 |
+
return firestore.client()
|
| 33 |
+
|
| 34 |
+
db = init_firestore()
|
| 35 |
+
|
| 36 |
+
def get_advice_by_id(doc_id: str):
|
| 37 |
+
"""
|
| 38 |
+
Fetch one advisory record by document ID.
|
| 39 |
+
"""
|
| 40 |
+
doc = db.collection(COLLECTION_NAME).document(str(doc_id)).get()
|
| 41 |
+
return doc.to_dict() if doc.exists else None
|