Skip to content

Commit 8e52fbe

Browse files
authored
chore(fix): Removed Python Custom Error Handler & Fixed Python Bug in ReportingByComment (#45)
* chore(fix): Removed Python custom error handler and replaced with HTTPException. Removed all files and instances related to custom Python error handler Fixed Python bug in ReportingByComment * Adding docstring * chore: corrected tests * (fix): implementing feedback changes & testing cli pipeline * (fix): increase wait time for integration tests * bug fix * bug fix - Devnull * Update run-python-tests.yml * Update run-python-tests.yml Remove tmate for debugging * Update run-python-tests.yml direction connection change * Update run-python-tests.yml Adding index creation * Update run-python-tests.yml * Update run-python-tests.yml * Update run-python-tests.yml * Update run-python-tests.yml
1 parent eec8914 commit 8e52fbe

10 files changed

Lines changed: 380 additions & 417 deletions

File tree

.github/workflows/run-python-tests.yml

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,58 @@ jobs:
3838
- name: Download sample data
3939
run: curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
4040

41-
- name: Add sample data to database
42-
run: mongorestore --archive=sampledata.archive --port=27017
41+
- name: Setup Database (Data & Indexes)
42+
run: |
43+
# 1. Restore the data
44+
mongorestore --archive=sampledata.archive --port=27017
45+
46+
# 2. Prepare the Search Index Definition
47+
echo '{
48+
"name": "movieSearchIndex",
49+
"database": "sample_mflix",
50+
"collectionName": "movies",
51+
"mappings": {
52+
"dynamic": false,
53+
"fields": {
54+
"plot": {"type": "string", "analyzer": "lucene.standard"},
55+
"fullplot": {"type": "string", "analyzer": "lucene.standard"},
56+
"directors": {"type": "string", "analyzer": "lucene.standard"},
57+
"writers": {"type": "string", "analyzer": "lucene.standard"},
58+
"cast": {"type": "string", "analyzer": "lucene.standard"}
59+
}
60+
}
61+
}' > search_index.json
62+
63+
# 3. Create the Search Index
64+
atlas deployments search indexes create \
65+
--deploymentName myLocalRs1 \
66+
--file search_index.json
67+
68+
# 4. Prepare the Vector Index Definition
69+
echo '{
70+
"name": "vector_index",
71+
"database": "sample_mflix",
72+
"collectionName": "embedded_movies",
73+
"type": "vectorSearch",
74+
"fields": [
75+
{
76+
"type": "vector",
77+
"path": "plot_embedding_voyage_3_large",
78+
"numDimensions": 2048,
79+
"similarity": "cosine"
80+
}
81+
]
82+
}' > vector_index.json
4383
84+
# 5. Create the Vector Index
85+
atlas deployments search indexes create \
86+
--deploymentName myLocalRs1 \
87+
--file vector_index.json
88+
89+
# 6. Wait for indexes to build
90+
echo "Waiting for indexes to build..."
91+
sleep 20
92+
4493
- name: Set up Python
4594
uses: actions/setup-python@v5
4695
with:
@@ -63,10 +112,10 @@ jobs:
63112

64113
- name: Run integration tests
65114
working-directory: mflix/server/python-fastapi
66-
run: pytest -m integration --verbose --tb=short --junit-xml=test-results-integration.xml || true
115+
run: pytest -m integration --verbose --tb=short --junit-xml=test-results-integration.xml
67116
env:
68-
MONGO_URI: mongodb://localhost:27017
69-
MONGO_DB: sample_mflix
117+
MONGO_URI: mongodb://localhost:27017/?directConnection=true
118+
MONGO_DB: sample_mflix
70119

71120
- name: Upload test results
72121
uses: actions/upload-artifact@v4

mflix/server/python-fastapi/main.py

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from fastapi import FastAPI
33
from fastapi.middleware.cors import CORSMiddleware
44
from src.routers import movies
5-
from src.utils.errorHandler import register_error_handlers
65
from src.database.mongo_client import db, get_collection
76

87
import os
@@ -15,8 +14,9 @@
1514
@asynccontextmanager
1615
async def lifespan(app: FastAPI):
1716
# Startup: Create search indexes
18-
await ensure_search_index()
19-
await vector_search_index()
17+
await ensure_mongodb_search_index()
18+
await ensure_vector_search_index()
19+
await ensure_standard_index()
2020

2121
# Print server information
2222
print(f"\n{'='*60}")
@@ -30,10 +30,9 @@ async def lifespan(app: FastAPI):
3030
# Add any cleanup code here
3131

3232

33-
async def ensure_search_index():
33+
async def ensure_mongodb_search_index():
3434
try:
3535
movies_collection = db.get_collection("movies")
36-
comments_collection = db.get_collection("comments")
3736

3837
# Check and create search index for movies collection
3938
result = await movies_collection.list_search_indexes()
@@ -71,7 +70,7 @@ async def ensure_search_index():
7170
)
7271

7372

74-
async def vector_search_index():
73+
async def ensure_vector_search_index():
7574
"""
7675
Creates vector search index on application startup if it doesn't already exist.
7776
This ensures the index is ready before any vector search requests are made.
@@ -114,6 +113,26 @@ async def vector_search_index():
114113
f"and verify the 'embedded_movies' collection exists with the required embedding field."
115114
)
116115

116+
async def ensure_standard_index():
117+
"""
118+
Creates a standard MongoDB index on the comments collection on application startup.
119+
This improves performance for queries filtering by movie_id such as ReportingByComments().
120+
"""
121+
122+
try:
123+
comments_collection = db.get_collection("comments")
124+
125+
existing_indexes_cursor = await comments_collection.list_indexes()
126+
existing_indexes = [index async for index in existing_indexes_cursor]
127+
index_names = [index.get("name") for index in existing_indexes]
128+
standard_index_name = "movie_id_index"
129+
if standard_index_name not in index_names:
130+
await comments_collection.create_index([("movie_id", 1)], name=standard_index_name)
131+
132+
except Exception as e:
133+
print(f"Failed to create standard index on 'comments' collection: {str(e)}. ")
134+
print(f"Performance may be degraded. Please check your MongoDB configuration.")
135+
117136

118137
app = FastAPI(lifespan=lifespan)
119138

@@ -127,6 +146,5 @@ async def vector_search_index():
127146
allow_headers=["*"],
128147
)
129148

130-
register_error_handlers(app)
131149
app.include_router(movies.router, prefix="/api/movies", tags=["movies"])
132150

mflix/server/python-fastapi/src/database/mongo_client.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,6 @@ def get_collection(name:str):
1818
def voyage_ai_available():
1919
"""Check if Voyage API Key is available and valid."""
2020
api_key = os.getenv("VOYAGE_API_KEY")
21+
if api_key is None or api_key =="your_voyage_api_key":
22+
return None
2123
return api_key is not None and api_key.strip() != ""

mflix/server/python-fastapi/src/models/models.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -127,22 +127,9 @@ class SuccessResponse(BaseModel, Generic[T]):
127127
timestamp: str
128128
pagination: Optional[Pagination] = None
129129

130-
131-
class ErrorDetails(BaseModel):
132-
message: str
133-
code: Optional[str]
134-
details: Optional[Any] = None
135-
136130
class BatchUpdateRequest(BaseModel):
137131
filter: MovieFilter
138132
update: UpdateMovieRequest
139133

140134
class BatchDeleteRequest(BaseModel):
141135
filter: MovieFilter
142-
143-
class ErrorResponse(BaseModel):
144-
success: bool = False
145-
message: str
146-
error: ErrorDetails
147-
timestamp: str
148-

0 commit comments

Comments
 (0)