Skip to content

Commit

Permalink
Handled exceptions in python files
Browse files Browse the repository at this point in the history
  • Loading branch information
Sai-ganesh-0004 committed Oct 19, 2024
1 parent 76ac737 commit ed215ed
Show file tree
Hide file tree
Showing 15 changed files with 702 additions and 659 deletions.
24 changes: 18 additions & 6 deletions API/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
from __future__ import annotations

import uvicorn
from fastapi import FastAPI
import logging
from fastapi import FastAPI, HTTPException

from API import route

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

Fastapp = FastAPI()

# API Router
Fastapp.include_router(route.router)


@Fastapp.get("/")
def read_root():
return {"Hello": "FASTAPI"}

try:
return {"Hello": "FASTAPI"}
except Exception as e:
logger.error(f"Error in root endpoint: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")

# function to run server of FastAPI
# Function to run FastAPI server
def run_fastapi_app():
uvicorn.run(Fastapp, host="127.0.0.1", port=8000)
try:
uvicorn.run(Fastapp, host="127.0.0.1", port=8000)
except Exception as e:
logger.error(f"Error starting FastAPI server: {e}")
raise
96 changes: 62 additions & 34 deletions API/database.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import annotations

from datetime import datetime
import logging
from pymongo import MongoClient, errors

from pymongo import MongoClient

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class Database:
def __init__(self, uri="mongodb://localhost:27017/", db_name="ImageDB"):
Expand All @@ -14,8 +17,13 @@ def __init__(self, uri="mongodb://localhost:27017/", db_name="ImageDB"):
uri (str): The uri of the MongoDB server. Defaults to 'mongodb://localhost:27017/'.
db_name (str): The name of the MongoDB database. Defaults to 'ImageDB'.
"""
self.client = MongoClient(uri)
self.db = self.client[db_name]
try:
self.client = MongoClient(uri)
self.db = self.client[db_name]
logger.info("Successfully connected to MongoDB.")
except errors.ConnectionError as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise

def find(self, collection, query=None):
"""
Expand All @@ -28,7 +36,11 @@ def find(self, collection, query=None):
Returns:
pymongo.cursor.Cursor: A cursor pointing to the results of the query.
"""
return self.db[collection].find(query)
try:
return self.db[collection].find(query)
except errors.PyMongoError as e:
logger.error(f"Error finding documents in {collection}: {e}")
return None

def insert_one(self, collection, document):
"""
Expand All @@ -41,8 +53,11 @@ def insert_one(self, collection, document):
Returns:
pymongo.results.InsertOneResult: The result of the insertion.
"""

return self.db[collection].insert_one(document)
try:
return self.db[collection].insert_one(document)
except errors.PyMongoError as e:
logger.error(f"Error inserting document into {collection}: {e}")
return None

def find_one(self, collection, filter, projection=None):
"""
Expand All @@ -56,7 +71,11 @@ def find_one(self, collection, filter, projection=None):
Returns:
dict: The document that matches the query, or None if no documents match.
"""
return self.db[collection].find_one(filter=filter, projection=projection)
try:
return self.db[collection].find_one(filter=filter, projection=projection)
except errors.PyMongoError as e:
logger.error(f"Error finding document in {collection}: {e}")
return None

def find_one_and_delete(self, collection, query):
"""
Expand All @@ -69,7 +88,11 @@ def find_one_and_delete(self, collection, query):
Returns:
dict: The document that matches the query, or None if no documents match.
"""
return self.db[collection].find_one_and_delete(query)
try:
return self.db[collection].find_one_and_delete(query)
except errors.PyMongoError as e:
logger.error(f"Error deleting document in {collection}: {e}")
return None

def update_one(self, collection, query, update):
"""
Expand All @@ -83,10 +106,12 @@ def update_one(self, collection, query, update):
Returns:
pymongo.results.UpdateResult: The result of the update.
"""
try:
return self.db[collection].update_one(query, update)
except errors.PyMongoError as e:
logger.error(f"Error updating document in {collection}: {e}")
return None

return self.db[collection].update_one(query, update)

# add a function for pipeline aggregation vector search
def vector_search(self, collection, embedding):
"""
Perform a vector similarity search on the given collection.
Expand All @@ -98,27 +123,30 @@ def vector_search(self, collection, embedding):
Returns:
list: A list of documents with the closest embedding to the query vector, sorted by score.
"""

result = self.db[collection].aggregate(
[
{
"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": embedding,
"numCandidates": 20,
"limit": 20,
try:
result = self.db[collection].aggregate(
[
{
"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": embedding,
"numCandidates": 20,
"limit": 20,
},
},
},
{
"$project": {
"_id": 0,
"Name": 1,
"Image": 1,
"score": {"$meta": "vectorSearchScore"},
{
"$project": {
"_id": 0,
"Name": 1,
"Image": 1,
"score": {"$meta": "vectorSearchScore"},
},
},
},
],
)
result_arr = [i for i in result]
return result_arr
],
)
result_arr = [i for i in result]
return result_arr
except errors.PyMongoError as e:
logger.error(f"Error performing vector search in {collection}: {e}")
return []
30 changes: 18 additions & 12 deletions API/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,21 @@ def format(self, record):
formatter = logging.Formatter(log_fmt)
return formatter.format(record)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.DEBUG)
stderr_handler.setFormatter(CustomFormatter())
logger.addHandler(stderr_handler)

file_handler = logging.FileHandler("app.log", mode="w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CustomFormatter(True))
logger.addHandler(file_handler)
try:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.DEBUG)
stderr_handler.setFormatter(CustomFormatter())
logger.addHandler(stderr_handler)

file_handler = logging.FileHandler("app.log", mode="w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CustomFormatter(True))
logger.addHandler(file_handler)

logging.info("Logging configuration initialized successfully.")
except Exception as e:
print(f"Error initializing logging configuration: {e}")
logging.error(f"Error initializing logging configuration: {e}")
Loading

0 comments on commit ed215ed

Please sign in to comment.