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

Bikes and users api bugs are fixed

parent 1252f699
No related branches found
No related tags found
1 merge request!3Pkxnew2
...@@ -140,11 +140,14 @@ async def read_available_bikes(): ...@@ -140,11 +140,14 @@ async def read_available_bikes():
@app.get("/bikes/{bike_id}", response_model=Bike) @app.get("/bikes/{bike_id}", response_model=Bike)
async def read_bike(bike_id: int): async def read_bike(bike_id: int):
cursor.execute('SELECT * FROM Bikes WHERE bike_id = ?', (bike_id,)) cursor.execute('SELECT * FROM Bikes WHERE bike_id = %s', (bike_id,))
bike = cursor.fetchone() bike = cursor.fetchone()
if bike is None: if bike is None:
raise HTTPException(status_code=404, detail="Bike not found") raise HTTPException(status_code=404, detail="Bike not found")
# Format the last_maintenance_date from datetime.date to string
last_maintenance_date_formatted = bike[6].strftime('%Y-%m-%d') if bike[6] else None
# Create a Bike object from the fetched data # Create a Bike object from the fetched data
bike_obj = Bike( bike_obj = Bike(
model=bike[1], model=bike[1],
...@@ -152,7 +155,7 @@ async def read_bike(bike_id: int): ...@@ -152,7 +155,7 @@ async def read_bike(bike_id: int):
current_location=bike[3], current_location=bike[3],
bike_condition=bike[4], bike_condition=bike[4],
price_per_hour=bike[5], price_per_hour=bike[5],
last_maintenance_date=bike[6], last_maintenance_date=last_maintenance_date_formatted,
maintenance_history=bike[7] maintenance_history=bike[7]
) )
......
...@@ -7,6 +7,7 @@ from pathlib import Path ...@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Optional from typing import Optional
from fastapi import HTTPException from fastapi import HTTPException
import mysql.connector import mysql.connector
from decimal import Decimal
app = FastAPI() app = FastAPI()
...@@ -214,11 +215,29 @@ async def read_rentals(): ...@@ -214,11 +215,29 @@ async def read_rentals():
@app.get("/rentals/{rental_id}", response_model=Rental) @app.get("/rentals/{rental_id}", response_model=Rental)
async def read_rental(rental_id: int): async def read_rental(rental_id: int):
cursor.execute('SELECT * FROM Rentals WHERE rental_id = ?', (rental_id,)) cursor.execute('SELECT * FROM Rentals WHERE rental_id = %s', (rental_id,))
rental = cursor.fetchone() rental = cursor.fetchone()
if rental is None: if rental is None:
raise HTTPException(status_code=404, detail="Rental not found") raise HTTPException(status_code=404, detail="Rental not found")
return rental
# Convert the tuple to a dictionary
rental_dict = {
'user_id': rental[1],
'bike_id': rental[2],
'year': rental[3],
'hour': rental[4],
'season': rental[5],
'holiday': bool(rental[6]),
'workingday': bool(rental[7]),
'weather': rental[8],
'temp': float(rental[9]),
'atemp': float(rental[10]),
'humidity': float(rental[11]),
'windspeed': float(rental[12]),
'count': rental[13]
}
return Rental(**rental_dict)
@app.put("/rentals/{rental_id}", response_model=Rental) @app.put("/rentals/{rental_id}", response_model=Rental)
......
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware # type: ignore
from typing import List
import sqlite3
from pathlib import Path
from typing import Optional
from fastapi import HTTPException # type: ignore
import mysql.connector
app = FastAPI()
# Allow requests from all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
# 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 Rentals table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS Rentals (
rental_id INTEGER PRIMARY KEY,
id INT,
user_id INT,
bike_id INT,
year INT,
hour INT,
season INT,
holiday BOOLEAN,
workingday BOOLEAN,
weather INT,
temp DECIMAL(5, 2),
atemp DECIMAL(5, 2),
humidity DECIMAL(5, 2),
windspeed DECIMAL(5, 2),
count INT,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
)
''')
conn.commit()
# Rental model
class Rental(BaseModel):
user_id: Optional[int] = None
bike_id: int
year: int
hour: int
season: int
holiday: bool
workingday: bool
weather: int
temp: float
atemp: float
humidity: float
windspeed: float
count: float
class PostRental(BaseModel):
id:Optional[int] = None
user_id: Optional[int] = None
bike_id: int
year: int
hour: int
season: int
holiday: bool
workingday: bool
weather: int
temp: float
atemp: float
humidity: float
windspeed: float
count: float
@app.post("/rentals/", response_model=Rental)
async def create_rental(rental: Rental):
try:
cursor.execute('''
INSERT INTO Rentals
(id,user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
rental.id,rental.user_id, rental.bike_id, rental.year, rental.hour,
rental.season, rental.holiday, rental.workingday, rental.weather,
rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count
))
conn.commit()
# Get the auto-generated id of the new rental
rental_id = cursor.lastrowid
# Return the created rental with the generated id
rental.id = rental_id
return rental
except Exception as e:
print(f"Error creating rental: {e}")
raise HTTPException(status_code=422, detail=str(e))
@app.get("/rentals/", response_model=List[Rental])
async def read_rentals():
cursor.execute('SELECT * FROM Rentals')
rentals = cursor.fetchall()
rental_objects = []
# for rental in rentals:
# rental_objects.append(Rental(
# id=rental[0],
# user_id=rental[1],
# bike_id=rental[2],
# year=rental[3],
# hour=rental[4],
# season=rental[5],
# holiday=bool(rental[6]),
# workingday=bool(rental[7]),
# weather=rental[8],
# temp=float(rental[9]),
# atemp=float(rental[10]),
# humidity=float(rental[11]),
# windspeed=float(rental[12]),
# count=int(rental[13]) # Convert to integer
# ))
for rental in rentals:
rental_objects.append(Rental(
user_id=rental[1],
bike_id=rental[2],
year=rental[3],
hour=rental[4],
season=rental[5],
holiday=bool(rental[6]),
workingday=bool(rental[7]),
weather=rental[8],
temp=float(rental[9]),
atemp=float(rental[10]),
humidity=float(rental[11]),
windspeed=float(rental[12]),
count=rental[13]
))
return rental_objects
@app.get("/rentals/{rental_id}", response_model=Rental)
async def read_rental(rental_id: int):
cursor.execute('SELECT * FROM Rentals WHERE rental_id = ?', (rental_id,))
rental_data = cursor.fetchone()
if rental_data is None:
raise HTTPException(status_code=404, detail="Rental not found")
# Construct a Rental instance from the tuple data
rental = Rental(
id=rental_data[0], # Assuming the rental_id is the first column in your table
user_id=rental_data[1],
bike_id=rental_data[2],
year=rental_data[3],
hour=rental_data[4],
season=rental_data[5],
holiday=bool(rental_data[6]),
workingday=bool(rental_data[7]),
weather=rental_data[8],
temp=float(rental_data[9]),
atemp=float(rental_data[10]),
humidity=float(rental_data[11]),
windspeed=float(rental_data[12]),
count=int(rental_data[13]) # Assuming count should be converted to int
)
return rental
@app.put("/rentals/{rental_id}", response_model=Rental)
async def update_rental(rental_id: int, rental: Rental):
try:
cursor.execute('''
UPDATE Rentals
SET user_id = ?, bike_id = ?, year = ?, hour = ?, season = ?,
holiday = ?, workingday = ?, weather = ?, temp = ?, atemp = ?,
humidity = ?, windspeed = ?, count = ?
WHERE rental_id = ?
''', (
rental.user_id, rental.bike_id, rental.year, rental.hour,
rental.season, rental.holiday, rental.workingday, rental.weather,
rental.temp, rental.atemp, rental.humidity, rental.windspeed,
rental.count, rental_id
))
conn.commit()
return rental
except sqlite3.OperationalError as e:
print("SQL error:", e)
raise HTTPException(status_code=400, detail=str(e))
@app.delete("/rentals/{rental_id}")
async def delete_rental(rental_id: int):
cursor.execute('DELETE FROM Rentals WHERE rental_id = ?', (rental_id,))
conn.commit()
return {"message": "Rental deleted successfully"}
...@@ -168,10 +168,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel): ...@@ -168,10 +168,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel):
for field, value in update_data.dict(exclude_none=True).items(): for field, value in update_data.dict(exclude_none=True).items():
if value is not None: if value is not None:
updates.append(f"{field} = %s") updates.append(f"{field} = %s")
if field in ["registration_date", "last_login"]: params.append(value)
params.append(value.strftime('%Y-%m-%d %H:%M:%S'))
else:
params.append(value)
if not updates: if not updates:
raise HTTPException(status_code=400, detail="No valid fields provided for update") raise HTTPException(status_code=400, detail="No valid fields provided for update")
...@@ -199,6 +196,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel): ...@@ -199,6 +196,7 @@ async def update_user(user_id: int, update_data: UpdateUserModel):
raise HTTPException(status_code=404, detail="Error updating user.") raise HTTPException(status_code=404, detail="Error updating user.")
@app.delete("/users/{user_id}") @app.delete("/users/{user_id}")
async def delete_user(user_id: int): async def delete_user(user_id: int):
cursor.execute('DELETE FROM Users WHERE user_id = %s', (user_id,)) cursor.execute('DELETE FROM Users WHERE user_id = %s', (user_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