This commit is contained in:
johnpccd 2025-05-24 06:27:04 +02:00
parent 56c8f7b944
commit 6a29cba09f
2 changed files with 44 additions and 14 deletions

View File

@ -10,7 +10,7 @@ class PyObjectId(ObjectId):
yield cls.validate yield cls.validate
@classmethod @classmethod
def validate(cls, v): def validate(cls, v, self_instance=None):
if not ObjectId.is_valid(v): if not ObjectId.is_valid(v):
raise ValueError('Invalid ObjectId') raise ValueError('Invalid ObjectId')
return ObjectId(v) return ObjectId(v)

View File

@ -29,13 +29,16 @@ class FirestoreProvider:
"""Connect to Firestore""" """Connect to Firestore"""
try: try:
if settings.GCS_CREDENTIALS_FILE and os.path.exists(settings.GCS_CREDENTIALS_FILE): if settings.GCS_CREDENTIALS_FILE and os.path.exists(settings.GCS_CREDENTIALS_FILE):
self.client = firestore.Client.from_service_account_json(settings.GCS_CREDENTIALS_FILE) self.client = firestore.Client.from_service_account_json(
settings.GCS_CREDENTIALS_FILE,
database='imagedb' # Use the specific database ID
)
else: else:
# Use application default credentials # Use application default credentials with specific database
self.client = firestore.Client() self.client = firestore.Client(database='imagedb')
self._db = self.client self._db = self.client
logger.info("Connected to Firestore") logger.info("Connected to Firestore database: imagedb")
return True return True
except Exception as e: except Exception as e:
logger.error(f"Failed to connect to Firestore: {e}") logger.error(f"Failed to connect to Firestore: {e}")
@ -71,23 +74,28 @@ class FirestoreProvider:
collection = self.get_collection(collection_name) collection = self.get_collection(collection_name)
# Handle ObjectId conversion for Firestore # Handle ObjectId conversion for Firestore
processed_data = {}
for key, value in data.items(): for key, value in data.items():
if hasattr(value, '__str__') and key != 'id': if value is None:
data[key] = str(value) processed_data[key] = None
elif hasattr(value, '__str__') and key != 'id':
processed_data[key] = str(value)
else:
processed_data[key] = value
# Handle special case for document ID # Handle special case for document ID
doc_id = None doc_id = None
if "_id" in data: if "_id" in processed_data:
doc_id = str(data["_id"]) doc_id = str(processed_data["_id"])
del data["_id"] del processed_data["_id"]
# Add document to Firestore # Add document to Firestore
if doc_id: if doc_id:
doc_ref = collection.document(doc_id) doc_ref = collection.document(doc_id)
doc_ref.set(data) doc_ref.set(processed_data)
return doc_id return doc_id
else: else:
doc_ref = collection.add(data) doc_ref = collection.add(processed_data)
return doc_ref[1].id return doc_ref[1].id
except Exception as e: except Exception as e:
logger.error(f"Error adding document to {collection_name}: {e}") logger.error(f"Error adding document to {collection_name}: {e}")
@ -109,6 +117,24 @@ class FirestoreProvider:
doc = doc_ref.get() doc = doc_ref.get()
if doc.exists: if doc.exists:
data = doc.to_dict() data = doc.to_dict()
# Properly handle None values and complex types
for key, value in data.items():
if value == 'None' or value == 'null':
data[key] = None
# Handle lists stored as strings
elif isinstance(value, str) and value.startswith('[') and value.endswith(']'):
try:
import ast
data[key] = ast.literal_eval(value)
except (SyntaxError, ValueError):
pass # Keep as string if conversion fails
# Handle dictionaries stored as strings
elif isinstance(value, str) and value.startswith('{') and value.endswith('}'):
try:
import ast
data[key] = ast.literal_eval(value)
except (SyntaxError, ValueError):
pass # Keep as string if conversion fails
data["_id"] = doc_id data["_id"] = doc_id
return data return data
return None return None
@ -154,9 +180,13 @@ class FirestoreProvider:
# Process data for Firestore # Process data for Firestore
processed_data = {} processed_data = {}
for key, value in data.items(): for key, value in data.items():
if key != "_id" and hasattr(value, '__str__'): if key == "_id":
continue
elif value is None:
processed_data[key] = None
elif hasattr(value, '__str__'):
processed_data[key] = str(value) processed_data[key] = str(value)
elif key != "_id": else:
processed_data[key] = value processed_data[key] = value
doc_ref = self.get_collection(collection_name).document(doc_id) doc_ref = self.get_collection(collection_name).document(doc_id)