Skip to content
Snippets Groups Projects
Commit 1252f699 authored by Sahu, Pratyush K (PG/T - Comp Sci & Elec Eng)'s avatar Sahu, Pratyush K (PG/T - Comp Sci & Elec Eng)
Browse files

Updated the Reviews api

parent ab988282
No related branches found
No related tags found
1 merge request!3Pkxnew2
......@@ -18,35 +18,6 @@ app.add_middleware(
)
# # SQLite connection
# parent_directory = Path(__file__).resolve().parent.parent
# db_file_path = parent_directory / "my_ride.db"
# # print(db_file_path)
# conn = sqlite3.connect(db_file_path)
# cursor = conn.cursor()
# # Create the Reviews table if it doesn't exist
# cursor.execute('''
# CREATE TABLE IF NOT EXISTS Reviews (
# review_id INTEGER PRIMARY KEY AUTOINCREMENT,
# user_id INT,
# bike_id INT,
# rating INT,
# comment TEXT,
# review_date DATETIME,
# FOREIGN KEY (user_id) REFERENCES Users(user_id),
# FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
# )
# ''')
# conn.commit()
# db_connection = mysql.connector.connect(
# host='database_mysql', # or '127.0.0.1' for IPv4 loopback
# port='3306', # Specify the port number here
# user='root',
# password='root_password',
# database='your_database'
# )
db_connection = mysql.connector.connect(
host='database-1.cz0ucmk42cu5.us-east-1.rds.amazonaws.com', # or '127.0.0.1' for IPv4 loopback
......@@ -67,6 +38,21 @@ class Review(BaseModel):
comment: str
review_date: str
class GetReview(BaseModel):
review_id:int
user_id: int
bike_id: int
rating: int
comment: str
review_date: str
class UpdateReview(BaseModel):
user_id: Optional[int] = None
bike_id: Optional[int] = None
rating: Optional[int] = None
comment: Optional[str] = None
review_date: Optional[str] = None
# Routes
@app.post("/reviews/", response_model=Review)
......@@ -79,7 +65,8 @@ async def create_review(review: Review):
review.user_id, review.bike_id, review.rating, review.comment, review.review_date
))
db_connection.commit()
return review
review_id = cursor.lastrowid # Get the last inserted id
return {**review.dict(), "review_id": review_id}
@app.get("/reviews/", response_model=List[Review])
......@@ -99,27 +86,60 @@ async def read_reviews():
return review_objects
@app.get("/reviews/{review_id}", response_model=Review)
@app.get("/reviews/{review_id}", response_model=GetReview)
async def read_review(review_id: int):
cursor.execute('SELECT * FROM Reviews WHERE review_id = %s', (review_id,))
# Execute the query to fetch the review
cursor.execute('SELECT review_id, user_id, bike_id, rating, comment, review_date FROM Reviews WHERE review_id = %s', (review_id,))
review = cursor.fetchone()
if review is None:
raise HTTPException(status_code=404, detail="Review not found")
return review
# Check if review_date is not None and format it as string
review_date_formatted = review[5].strftime('%Y-%m-%d %H:%M:%S') if review[5] else None
# Return the formatted review data using the GetReview model
return GetReview(
review_id=review[0],
user_id=review[1],
bike_id=review[2],
rating=review[3],
comment=review[4],
review_date=review_date_formatted
)
@app.put("/reviews/{review_id}", response_model=Review)
async def update_review(review_id: int, review: Review):
cursor.execute('''
UPDATE Reviews
SET user_id = %s, bike_id = %s, rating = %s, comment = %s, review_date = %s
WHERE review_id = %s
''', (
review.user_id, review.bike_id, review.rating, review.comment,
review.review_date, review_id
))
async def update_review(review_id: int, review_update: UpdateReview):
updates = []
values = []
for field, value in review_update.dict(exclude_none=True).items():
updates.append(f"{field} = %s")
values.append(value)
if not updates:
raise HTTPException(status_code=400, detail="No fields provided for update")
update_stmt = f"UPDATE Reviews SET {', '.join(updates)} WHERE review_id = %s"
values.append(review_id)
cursor.execute(update_stmt, tuple(values))
db_connection.commit()
return review
# Fetch the updated review data
cursor.execute('SELECT review_id, user_id, bike_id, rating, comment, review_date FROM Reviews WHERE review_id = %s', (review_id,))
updated_review = cursor.fetchone()
if updated_review:
review_dict = {
'review_id': updated_review[0],
'user_id': updated_review[1],
'bike_id': updated_review[2],
'rating': updated_review[3],
'comment': updated_review[4],
'review_date': updated_review[5].strftime('%Y-%m-%d %H:%M:%S') if updated_review[5] else None
}
return Review(**review_dict)
else:
raise HTTPException(status_code=404, detail="Error updating review.")
@app.delete("/reviews/{review_id}")
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment