Skip to content
Snippets Groups Projects

added docker related code

parent ebf4938e
No related branches found
No related tags found
No related merge requests found
...@@ -2,6 +2,7 @@ from fastapi import FastAPI, HTTPException ...@@ -2,6 +2,7 @@ from fastapi import FastAPI, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
import sqlite3 import sqlite3
import mysql.connector
from pathlib import Path from pathlib import Path
from typing import Optional, Tuple, List from typing import Optional, Tuple, List
...@@ -16,37 +17,46 @@ app.add_middleware( ...@@ -16,37 +17,46 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# SQLite connection # # SQLite connection
# SQLite connection # # SQLite connection
# # parent_directory = Path(__file__).resolve().parent.parent
# # db_file_path = parent_directory / "my_ride.db"
# # # print(db_file_path)
# parent_directory = Path(__file__).resolve().parent.parent # parent_directory = Path(__file__).resolve().parent.parent
# # Specify the path to the SQLite database file in the data directory
# db_file_path = parent_directory / "my_ride.db" # db_file_path = parent_directory / "my_ride.db"
# # print(db_file_path)
# # Check if the database file exists
parent_directory = Path(__file__).resolve().parent.parent # if not db_file_path.exists():
# Specify the path to the SQLite database file in the data directory # # If the database file doesn't exist, use a local database file from the same location
db_file_path = parent_directory / "my_ride.db" # local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
# db_file_path = local_db_file_path
# Check if the database file exists
if not db_file_path.exists(): # conn = sqlite3.connect(db_file_path)
# If the database file doesn't exist, use a local database file from the same location
local_db_file_path = Path(__file__).resolve().parent / "local_bike.db" # cursor = conn.cursor()
db_file_path = local_db_file_path
db_connection = mysql.connector.connect(
conn = sqlite3.connect(db_file_path) host='database_mysql', # or '127.0.0.1' for IPv4 loopback
port='3306', # Specify the port number here
cursor = conn.cursor() user='root',
password='root_password',
# Create the Admins table if it doesn't exist database='your_database'
cursor.execute(''' )
CREATE TABLE IF NOT EXISTS Admins ( cursor = db_connection.cursor()
admin_id INTEGER PRIMARY KEY,
username TEXT, # # Create the Admins table if it doesn't exist
password TEXT, # cursor.execute('''
email TEXT, # CREATE TABLE IF NOT EXISTS Admins (
phone_number TEXT # admin_id INTEGER PRIMARY KEY,
) # username TEXT,
''') # password TEXT,
conn.commit() # email TEXT,
# phone_number TEXT
# )
# ''')
# conn.commit()
# Admin model # Admin model
...@@ -74,11 +84,11 @@ async def create_admin(admin: Admin): ...@@ -74,11 +84,11 @@ async def create_admin(admin: Admin):
cursor.execute(''' cursor.execute('''
INSERT INTO Admins INSERT INTO Admins
(username, password, email, phone_number) (username, password, email, phone_number)
VALUES (?, ?, ?, ?) VALUES (%s, %s, %s, %s)
''', ( ''', (
admin.username, admin.password, admin.email, admin.phone_number admin.username, admin.password, admin.email, admin.phone_number
)) ))
conn.commit() db_connection.commit()
return AdminResponse( return AdminResponse(
username=admin.username, username=admin.username,
email=admin.email, email=admin.email,
......
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from typing import List
import sqlite3
from pathlib import Path
from typing import Optional
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 ########################
# conn = sqlite3.connect('bikes.db')
# Get the path to the parent directory of your FastAPI application
# parent_directory = Path(__file__).resolve().parent.parent
# # print(parent_directory)
# # Specify the path to the SQLite database file in the data directory
# db_file_path = parent_directory / "my_ride.db"
# # Check if the database file exists
# if not db_file_path.exists():
# # If the database file doesn't exist, use a local database file from the same location
# local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
# db_file_path = local_db_file_path
# # print(db_file_path)
# conn = sqlite3.connect(db_file_path)
# cursor = conn.cursor()
######################### SQLite connection ##########################
######################### mysql connectivity #########################
# MySQL connection
# db_connection = mysql.connector.connect(
# host="localhost", # Use the service name defined in docker-compose.yml
# user="your_username",
# password="your_password",
# database="your_database"
# )
db_connection = mysql.connector.connect(
host='localhost', # or '127.0.0.1' for IPv4 loopback
port='3306', # Specify the port number here
user='root',
password='root_password',
database='your_database'
)
cursor = db_connection.cursor()
######################### mysql connectivity #########################
# # Bike model
# class Bike(BaseModel):
# model: str
# status: Optional[str]
# location: str
# condition: str
# price_per_hour: float
# last_maintenance_date: str
# maintenance_history: str
# class BikeResponse(BaseModel):
# id: int
# model: str
# status: Optional[str]
# location: str
# condition: str
# price_per_hour: float
# last_maintenance_date: str
# maintenance_history: str
# Bike model
class Bike(BaseModel):
bike_id: int
model: str
bike_status: Optional[str]
current_location: str
bike_condition: str
price_per_hour: float
last_maintenance_date: str
maintenance_history: str
class BikeResponse(BaseModel):
bike_id: int
model: str
bike_status: Optional[str]
current_location: str
bike_condition: str
price_per_hour: float
last_maintenance_date: str
maintenance_history: str
# # Routes
# @app.post("/bikes/", response_model=Bike)
# async def create_bike(bike: Bike):
# cursor.execute('''
# INSERT INTO Bikes
# (model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
# VALUES (?, ?, ?, ?, ?, ?, ?)
# ''', (
# bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
# bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
# ))
# conn.commit()
# return bike
# @app.get("/bikes/", response_model=List[BikeResponse])
# async def read_bikes():
# cursor.execute('SELECT * FROM Bikes')
# bikes = cursor.fetchall()
# bike_objects = []
# for bike in bikes:
# bike_obj = BikeResponse(
# id=bike[0],
# model=bike[1],
# status=bike[2],
# location=bike[3],
# condition=bike[4],
# price_per_hour=bike[5],
# last_maintenance_date=bike[6],
# maintenance_history=bike[7]
# )
# bike_objects.append(bike_obj)
# return bike_objects
# # Routes
# @app.post("/bikes/", response_model=Bike)
# async def create_bike(bike: Bike):
# cursor.execute('''
# INSERT INTO Bikes
# (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
# VALUES (?, ?, ?, ?, ?, ?, ?)
# ''', (
# bike.bike_id, bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
# bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
# ))
# conn.commit()
# return bike
# @app.post("/bikes/", response_model=Bike)
# async def create_bike(bike: Bike):
# try:
# # Cast price_per_hour to float
# bike.price_per_hour = float(bike.price_per_hour)
# sql_statement = '''
# INSERT INTO Bikes
# (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
# VALUES (?, ?, ?, ?, ?, ?, ?, ?)
# '''
# values = (
# bike.bike_id, bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
# bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
# )
# print("Executing SQL statement:", sql_statement)
# print("Values:", values)
# cursor.execute(sql_statement, values)
# db_connection.commit()
# return bike
# except Exception as e:
# # Log the exception or print it for debugging
# print("An error occurred during the POST request:", e)
# # Raise an HTTPException with a 500 Internal Server Error status code
# raise HTTPException(status_code=500, detail="Internal Server Error")
@app.post("/bikes/", response_model=Bike)
async def create_bike(bike: Bike):
try:
# Cast price_per_hour to float
bike.price_per_hour = float(bike.price_per_hour)
# Remove trailing whitespaces from the string fields
model = bike.model.strip()
current_location = bike.current_location.strip()
bike_condition = bike.bike_condition.strip()
last_maintenance_date = bike.last_maintenance_date.strip()
maintenance_history = bike.maintenance_history.strip()
# Remove trailing commas from the string fields
model = model.rstrip(',')
current_location = current_location.rstrip(',')
bike_condition = bike_condition.rstrip(',')
maintenance_history = maintenance_history.rstrip(',')
sql_statement = '''
INSERT INTO Bikes
(bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
'''
values = (
bike.bike_id, model, bike.bike_status, current_location, bike_condition,
bike.price_per_hour, last_maintenance_date, maintenance_history
)
print("Executing SQL statement:", sql_statement)
print("Values:", values)
cursor.execute(sql_statement, values)
db_connection.commit()
return bike
except Exception as e:
# Log the exception or print it for debugging
print("An error occurred during the POST request:", e)
# Raise an HTTPException with a 500 Internal Server Error status code
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.get("/bikes/", response_model=List[BikeResponse])
async def read_bikes():
cursor.execute('SELECT * FROM Bikes')
bikes = cursor.fetchall()
bike_objects = []
for bike in bikes:
bike_obj = BikeResponse(
bike_id=bike[0],
model=bike[1],
bike_status=bike[2],
current_location=bike[3],
bike_condition=bike[4],
price_per_hour=bike[5],
last_maintenance_date=str(bike[6]), # Convert date to string
maintenance_history=bike[7]
)
bike_objects.append(bike_obj)
return bike_objects
@app.get("/bikes/{bike_id}", response_model=Bike)
async def read_bike(bike_id: int):
cursor.execute('SELECT * FROM Bikes WHERE bike_id = ?', (bike_id,))
bike = cursor.fetchone()
if bike is None:
raise HTTPException(status_code=404, detail="Bike not found")
# Create a Bike object from the fetched data
bike_obj = Bike(
model=bike[1],
status=bike[2],
location=bike[3],
condition=bike[4],
price_per_hour=bike[5],
last_maintenance_date=bike[6],
maintenance_history=bike[7]
)
return bike_obj
@app.put("/bikes/{bike_id}", response_model=Bike)
async def update_bike(bike_id: int, bike: Bike):
cursor.execute('''
UPDATE Bikes
SET model = ?, status = ?, location = ?, condition = ?,
price_per_hour = ?, last_maintenance_date = ?, maintenance_history = ?
WHERE bike_id = ?
''', (
bike.model, bike.status, bike.location, bike.condition,
bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history, bike_id
))
conn.commit()
return bike
@app.delete("/bikes/{bike_id}")
async def delete_bike(bike_id: int):
cursor.execute('DELETE FROM Bikes WHERE bike_id = ?', (bike_id,))
conn.commit()
return {"message": "Bike deleted successfully"}
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
...@@ -5,6 +6,7 @@ from typing import List ...@@ -5,6 +6,7 @@ from typing import List
import sqlite3 import sqlite3
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
import mysql.connector
app = FastAPI() app = FastAPI()
...@@ -17,44 +19,48 @@ app.add_middleware( ...@@ -17,44 +19,48 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# SQLite connection
# conn = sqlite3.connect('bikes.db')
# Get the path to the parent directory of your FastAPI application
parent_directory = Path(__file__).resolve().parent.parent
# print(parent_directory)
# Specify the path to the SQLite database file in the data directory
db_file_path = parent_directory / "my_ride.db"
# Check if the database file exists
if not db_file_path.exists():
# If the database file doesn't exist, use a local database file from the same location
local_db_file_path = Path(__file__).resolve().parent / "local_bike.db"
db_file_path = local_db_file_path
# print(db_file_path)
conn = sqlite3.connect(db_file_path)
cursor = conn.cursor() # db_connection = mysql.connector.connect(
# host="localhost", # Use the service name defined in docker-compose.yml
# user="your_username",
# password="your_password",
# database="your_database"
# )
# db_connection = mysql.connector.connect(
# host='localhost', # 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_mysql', # or '127.0.0.1' for IPv4 loopback
port='3306', # Specify the port number here
user='root',
password='root_password',
database='your_database'
)
cursor = db_connection.cursor()
# Bike model # Bike model
class Bike(BaseModel): class Bike(BaseModel):
model: str model: str
status: Optional[str] bike_status: Optional[str]
location: str current_location: str
condition: str bike_condition: str
price_per_hour: float price_per_hour: float
last_maintenance_date: str last_maintenance_date: str
maintenance_history: str maintenance_history: str
class BikeResponse(BaseModel): class BikeResponse(BaseModel):
id: int bike_id: int
model: str model: str
status: Optional[str] bike_status: Optional[str]
location: str current_location: str
condition: str bike_condition: str
price_per_hour: float price_per_hour: float
last_maintenance_date: str last_maintenance_date: str
maintenance_history: str maintenance_history: str
...@@ -63,18 +69,35 @@ class BikeResponse(BaseModel): ...@@ -63,18 +69,35 @@ class BikeResponse(BaseModel):
# Routes # Routes
@app.post("/bikes/", response_model=Bike) @app.post("/bikes/", response_model=Bike)
async def create_bike(bike: Bike): async def create_bike(bike: Bike):
cursor.execute(''' try:
INSERT INTO Bikes # Cast price_per_hour to float
(model, status, location, condition, price_per_hour, last_maintenance_date, maintenance_history) bike.price_per_hour = float(bike.price_per_hour)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', ( sql_statement = '''
bike.model, bike.status, bike.location, bike.condition, INSERT INTO Bikes
bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history (model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
)) VALUES (%s, %s, %s, %s, %s, %s, %s)
conn.commit() '''
return bike values = (
bike.model, bike.bike_status, bike.current_location, bike.bike_condition,
bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history
)
print("Executing SQL statement:", sql_statement)
print("Values:", values)
cursor.execute(sql_statement, values)
db_connection.commit()
return bike
except mysql.connector.Error as e:
# Log the MySQL error for debugging
print("MySQL Error:", e)
# Raise an HTTPException with a 500 Internal Server Error status code
raise HTTPException(status_code=500, detail="Internal Server Error")
except Exception as e:
# Log other exceptions for debugging
print("An error occurred during the POST request:", e)
# Raise an HTTPException with a 500 Internal Server Error status code
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.get("/bikes/", response_model=List[BikeResponse]) @app.get("/bikes/", response_model=List[BikeResponse])
async def read_bikes(): async def read_bikes():
...@@ -83,13 +106,13 @@ async def read_bikes(): ...@@ -83,13 +106,13 @@ async def read_bikes():
bike_objects = [] bike_objects = []
for bike in bikes: for bike in bikes:
bike_obj = BikeResponse( bike_obj = BikeResponse(
id=bike[0], bike_id=bike[0],
model=bike[1], model=bike[1],
status=bike[2], bike_status=bike[2],
location=bike[3], current_location=bike[3],
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=str(bike[6]), # Convert date to string
maintenance_history=bike[7] maintenance_history=bike[7]
) )
bike_objects.append(bike_obj) bike_objects.append(bike_obj)
...@@ -128,12 +151,13 @@ async def update_bike(bike_id: int, bike: Bike): ...@@ -128,12 +151,13 @@ async def update_bike(bike_id: int, bike: Bike):
bike.model, bike.status, bike.location, bike.condition, bike.model, bike.status, bike.location, bike.condition,
bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history, bike_id bike.price_per_hour, bike.last_maintenance_date, bike.maintenance_history, bike_id
)) ))
conn.commit() db_connection.commit()
return bike return bike
@app.delete("/bikes/{bike_id}") @app.delete("/bikes/{bike_id}")
async def delete_bike(bike_id: int): async def delete_bike(bike_id: int):
cursor.execute('DELETE FROM Bikes WHERE bike_id = ?', (bike_id,)) cursor.execute('DELETE FROM Bikes WHERE bike_id = ?', (bike_id,))
conn.commit() db_connection.commit()
return {"message": "Bike deleted successfully"} return {"message": "Bike deleted successfully"}
...@@ -6,6 +6,7 @@ import sqlite3 ...@@ -6,6 +6,7 @@ import sqlite3
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
from fastapi import HTTPException from fastapi import HTTPException
import mysql.connector
app = FastAPI() app = FastAPI()
...@@ -18,38 +19,46 @@ app.add_middleware( ...@@ -18,38 +19,46 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# SQLite connection # # SQLite connection
parent_directory = Path(__file__).resolve().parent.parent # parent_directory = Path(__file__).resolve().parent.parent
db_file_path = parent_directory / "my_ride.db" # db_file_path = parent_directory / "my_ride.db"
# print(db_file_path) # # print(db_file_path)
conn = sqlite3.connect(db_file_path) # conn = sqlite3.connect(db_file_path)
# cursor = conn.cursor()
cursor = conn.cursor() db_connection = mysql.connector.connect(
host='database_mysql', # or '127.0.0.1' for IPv4 loopback
# Create the Rentals table if it doesn't exist port='3306', # Specify the port number here
cursor.execute(''' user='root',
CREATE TABLE IF NOT EXISTS Rentals ( password='root_password',
rental_id INTEGER PRIMARY KEY, database='your_database'
id INT, )
user_id INT,
bike_id INT, cursor = db_connection.cursor()
year INT,
hour INT, # # Create the Rentals table if it doesn't exist
season INT, # cursor.execute('''
holiday BOOLEAN, # CREATE TABLE IF NOT EXISTS Rentals (
workingday BOOLEAN, # rental_id INTEGER PRIMARY KEY,
weather INT, # id INT,
temp DECIMAL(5, 2), # user_id INT,
atemp DECIMAL(5, 2), # bike_id INT,
humidity DECIMAL(5, 2), # year INT,
windspeed DECIMAL(5, 2), # hour INT,
count INT, # season INT,
FOREIGN KEY (user_id) REFERENCES Users(user_id), # holiday BOOLEAN,
FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id) # workingday BOOLEAN,
) # weather INT,
''') # temp DECIMAL(5, 2),
conn.commit() # 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 # Rental model
...@@ -133,13 +142,13 @@ async def create_rental(rental: Rental): ...@@ -133,13 +142,13 @@ async def create_rental(rental: Rental):
cursor.execute(''' cursor.execute('''
INSERT INTO Rentals INSERT INTO Rentals
(user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) (user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
''', ( ''', (
rental.user_id, rental.bike_id, rental.year, rental.hour, rental.user_id, rental.bike_id, rental.year, rental.hour,
rental.season, rental.holiday, rental.workingday, rental.weather, rental.season, rental.holiday, rental.workingday, rental.weather,
rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count
)) ))
conn.commit() db_connection.commit()
# Get the auto-generated id of the new rental # Get the auto-generated id of the new rental
rental_id = cursor.lastrowid rental_id = cursor.lastrowid
# Return the created rental with the generated id # Return the created rental with the generated id
...@@ -218,12 +227,12 @@ async def update_rental(rental_id: int, rental: Rental): ...@@ -218,12 +227,12 @@ async def update_rental(rental_id: int, rental: Rental):
rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.temp, rental.atemp, rental.humidity, rental.windspeed,
rental.count, rental_id rental.count, rental_id
)) ))
conn.commit() db_connection.commit()
return rental return rental
@app.delete("/rentals/{rental_id}") @app.delete("/rentals/{rental_id}")
async def delete_rental(rental_id: int): async def delete_rental(rental_id: int):
cursor.execute('DELETE FROM Rentals WHERE rental_id = ?', (rental_id,)) cursor.execute('DELETE FROM Rentals WHERE rental_id = ?', (rental_id,))
conn.commit() db_connection.commit()
return {"message": "Rental deleted successfully"} return {"message": "Rental deleted successfully"}
...@@ -5,6 +5,7 @@ from typing import List ...@@ -5,6 +5,7 @@ from typing import List
import sqlite3 import sqlite3
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
import mysql.connector
app = FastAPI() app = FastAPI()
# Allow requests from all origins # Allow requests from all origins
...@@ -17,28 +18,36 @@ app.add_middleware( ...@@ -17,28 +18,36 @@ app.add_middleware(
) )
# SQLite connection # # SQLite connection
parent_directory = Path(__file__).resolve().parent.parent # parent_directory = Path(__file__).resolve().parent.parent
db_file_path = parent_directory / "my_ride.db" # db_file_path = parent_directory / "my_ride.db"
# print(db_file_path) # # print(db_file_path)
conn = sqlite3.connect(db_file_path) # conn = sqlite3.connect(db_file_path)
# cursor = conn.cursor()
cursor = conn.cursor()
# # Create the Reviews table if it doesn't exist
# Create the Reviews table if it doesn't exist # cursor.execute('''
cursor.execute(''' # CREATE TABLE IF NOT EXISTS Reviews (
CREATE TABLE IF NOT EXISTS Reviews ( # review_id INTEGER PRIMARY KEY AUTOINCREMENT,
review_id INTEGER PRIMARY KEY AUTOINCREMENT, # user_id INT,
user_id INT, # bike_id INT,
bike_id INT, # rating INT,
rating INT, # comment TEXT,
comment TEXT, # review_date DATETIME,
review_date DATETIME, # FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (user_id) REFERENCES Users(user_id), # FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id)
FOREIGN KEY (bike_id) REFERENCES Bikes(bike_id) # )
) # ''')
''') # conn.commit()
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'
)
cursor = db_connection.cursor()
# Review model # Review model
...@@ -56,11 +65,11 @@ async def create_review(review: Review): ...@@ -56,11 +65,11 @@ async def create_review(review: Review):
cursor.execute(''' cursor.execute('''
INSERT INTO Reviews INSERT INTO Reviews
(user_id, bike_id, rating, comment, review_date) (user_id, bike_id, rating, comment, review_date)
VALUES (?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s)
''', ( ''', (
review.user_id, review.bike_id, review.rating, review.comment, review.review_date review.user_id, review.bike_id, review.rating, review.comment, review.review_date
)) ))
conn.commit() db_connection.commit()
return review return review
...@@ -75,7 +84,7 @@ async def read_reviews(): ...@@ -75,7 +84,7 @@ async def read_reviews():
bike_id=review[1], bike_id=review[1],
rating=review[2], rating=review[2],
comment=review[3], comment=review[3],
review_date=review[4] review_date=review[4].strftime('%Y-%m-%d %H:%M:%S')
) )
review_objects.append(review_obj) review_objects.append(review_obj)
return review_objects return review_objects
...@@ -83,7 +92,7 @@ async def read_reviews(): ...@@ -83,7 +92,7 @@ async def read_reviews():
@app.get("/reviews/{review_id}", response_model=Review) @app.get("/reviews/{review_id}", response_model=Review)
async def read_review(review_id: int): async def read_review(review_id: int):
cursor.execute('SELECT * FROM Reviews WHERE review_id = ?', (review_id,)) cursor.execute('SELECT * FROM Reviews WHERE review_id = %s', (review_id,))
review = cursor.fetchone() review = cursor.fetchone()
if review is None: if review is None:
raise HTTPException(status_code=404, detail="Review not found") raise HTTPException(status_code=404, detail="Review not found")
...@@ -94,18 +103,18 @@ async def read_review(review_id: int): ...@@ -94,18 +103,18 @@ async def read_review(review_id: int):
async def update_review(review_id: int, review: Review): async def update_review(review_id: int, review: Review):
cursor.execute(''' cursor.execute('''
UPDATE Reviews UPDATE Reviews
SET user_id = ?, bike_id = ?, rating = ?, comment = ?, review_date = ? SET user_id = %s, bike_id = %s, rating = %s, comment = %s, review_date = %s
WHERE review_id = ? WHERE review_id = %s
''', ( ''', (
review.user_id, review.bike_id, review.rating, review.comment, review.user_id, review.bike_id, review.rating, review.comment,
review.review_date, review_id review.review_date, review_id
)) ))
conn.commit() db_connection.commit()
return review return review
@app.delete("/reviews/{review_id}") @app.delete("/reviews/{review_id}")
async def delete_review(review_id: int): async def delete_review(review_id: int):
cursor.execute('DELETE FROM Reviews WHERE review_id = ?', (review_id,)) cursor.execute('DELETE FROM Reviews WHERE review_id = %s', (review_id,))
conn.commit() db_connection.commit()
return {"message": "Review deleted successfully"} return {"message": "Review deleted successfully"}
INSERT INTO Bikes (bike_id, model, bike_status, current_location, bike_condition, price_per_hour, last_maintenance_date, maintenance_history)
VALUES
(101, 'Mountain Bike', 'available', 'Central Park', 'good', 10.00, '2024-03-25', 'Cleaned and lubricated chain');
INSERT INTO Users (user_id, username, password, email, phone_number, credit_card_info, registration_date, last_login)
VALUES
(1, 'john_doe', 'password123', 'john@example.com', '+1234567890', '**** **** **** 1234', '2024-03-28 10:00:00', '2024-03-28 10:00:00');
INSERT INTO Rentals (rental_id, id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count)
VALUES
(1, 1001, 1, 101, 2024, 10, 1, 0, 1, 1, 15.5, 18.2, 67, 12.0, 3);
INSERT INTO Reviews (review_id, user_id, bike_id, rating, comment, review_date)
VALUES
(1, 1, 101, 4, 'Great bike for off-road trails!', '2024-03-29 12:30:00');
INSERT INTO Admins (admin_id, username, password, email, phone_number)
VALUES
(1, 'admin1', 'adminpass', 'admin1@example.com', '+1122334455');
CREATE TABLE Users (
user_id INT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255),
phone_number VARCHAR(20),
credit_card_info VARCHAR(255),
registration_date DATETIME,
last_login DATETIME
);
CREATE TABLE Bikes (
bike_id INT PRIMARY KEY,
model VARCHAR(255),
bike_status VARCHAR(50),
current_location VARCHAR(255),
bike_condition VARCHAR(50),
price_per_hour DECIMAL(10, 2),
last_maintenance_date DATE,
maintenance_history TEXT
);
CREATE TABLE Rentals (
rental_id INT 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)
);
CREATE TABLE Reviews (
review_id INT PRIMARY KEY,
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)
);
CREATE TABLE Admins (
admin_id INT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255),
phone_number VARCHAR(20)
);
...@@ -3,6 +3,7 @@ from pydantic import BaseModel ...@@ -3,6 +3,7 @@ from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from typing import List from typing import List
import sqlite3 import sqlite3
import mysql.connector
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
...@@ -17,29 +18,37 @@ app.add_middleware( ...@@ -17,29 +18,37 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# SQLite connection # # SQLite connection
parent_directory = Path(__file__).resolve().parent.parent # parent_directory = Path(__file__).resolve().parent.parent
db_file_path = parent_directory / "my_ride.db" # db_file_path = parent_directory / "my_ride.db"
# print(db_file_path) # # print(db_file_path)
conn = sqlite3.connect(db_file_path) # conn = sqlite3.connect(db_file_path)
cursor = conn.cursor() # cursor = conn.cursor()
# Create the Users table if it doesn't exist # # Create the Users table if it doesn't exist
cursor.execute(''' # cursor.execute('''
CREATE TABLE IF NOT EXISTS Users ( # CREATE TABLE IF NOT EXISTS Users (
user_id INTEGER PRIMARY KEY, # user_id INTEGER PRIMARY KEY,
username TEXT, # username TEXT,
password TEXT, # password TEXT,
email TEXT, # email TEXT,
phone_number TEXT, # phone_number TEXT,
credit_card_info TEXT, # credit_card_info TEXT,
registration_date DATETIME, # registration_date DATETIME,
last_login DATETIME # last_login DATETIME
) # )
''') # ''')
conn.commit() # 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'
)
cursor = db_connection.cursor()
class User(BaseModel): class User(BaseModel):
username: str username: str
...@@ -72,7 +81,7 @@ async def read_users(): ...@@ -72,7 +81,7 @@ async def read_users():
username=user[1], username=user[1],
email=user[2], email=user[2],
phone_number=user[3], phone_number=user[3],
registration_date=user[4] registration_date=user[4].strftime('%Y-%m-%d %H:%M:%S')
) )
user_objects.append(user_obj) user_objects.append(user_obj)
return user_objects return user_objects
...@@ -87,7 +96,7 @@ async def create_user(user: User): ...@@ -87,7 +96,7 @@ async def create_user(user: User):
cursor.execute(''' cursor.execute('''
INSERT INTO Users INSERT INTO Users
(username, password, email, phone_number, registration_date) (username, password, email, phone_number, registration_date)
VALUES (?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s)
''', ( ''', (
user.username, user.password, user.email, user.phone_number, user.username, user.password, user.email, user.phone_number,
user.registration_date user.registration_date
...@@ -96,7 +105,7 @@ async def create_user(user: User): ...@@ -96,7 +105,7 @@ async def create_user(user: User):
cursor.execute(''' cursor.execute('''
INSERT INTO Users INSERT INTO Users
(username, password, email, phone_number, registration_date, last_login) (username, password, email, phone_number, registration_date, last_login)
VALUES (?, ?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s)
''', ( ''', (
user.username, user.password, user.email, user.phone_number, user.username, user.password, user.email, user.phone_number,
user.registration_date, user.last_login user.registration_date, user.last_login
...@@ -105,7 +114,7 @@ async def create_user(user: User): ...@@ -105,7 +114,7 @@ async def create_user(user: User):
cursor.execute(''' cursor.execute('''
INSERT INTO Users INSERT INTO Users
(username, password, email, phone_number, credit_card_info, registration_date) (username, password, email, phone_number, credit_card_info, registration_date)
VALUES (?, ?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s)
''', ( ''', (
user.username, user.password, user.email, user.phone_number, user.username, user.password, user.email, user.phone_number,
user.credit_card_info, user.registration_date user.credit_card_info, user.registration_date
...@@ -114,12 +123,12 @@ async def create_user(user: User): ...@@ -114,12 +123,12 @@ async def create_user(user: User):
cursor.execute(''' cursor.execute('''
INSERT INTO Users INSERT INTO Users
(username, password, email, phone_number, credit_card_info, registration_date, last_login) (username, password, email, phone_number, credit_card_info, registration_date, last_login)
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (%s, %s, %s, %s, %s)
''', ( ''', (
user.username, user.password, user.email, user.phone_number, user.username, user.password, user.email, user.phone_number,
user.credit_card_info, user.registration_date, user.last_login user.credit_card_info, user.registration_date, user.last_login
)) ))
conn.commit() db_connection.commit()
return user return user
...@@ -137,19 +146,19 @@ async def read_user(user_id: int): ...@@ -137,19 +146,19 @@ async def read_user(user_id: int):
async def update_user(user_id: int, user: User): async def update_user(user_id: int, user: User):
cursor.execute(''' cursor.execute('''
UPDATE Users UPDATE Users
SET username = ?, password = ?, email = ?, phone_number = ?, SET username = %s, password = %s, email = %s, phone_number = %s,
credit_card_info = ?, registration_date = ?, last_login = ? credit_card_info = %s, registration_date = %s, last_login = %s
WHERE user_id = ? WHERE user_id = %s
''', ( ''', (
user.username, user.password, user.email, user.phone_number, user.username, user.password, user.email, user.phone_number,
user.credit_card_info, user.registration_date, user.last_login, user_id user.credit_card_info, user.registration_date, user.last_login, user_id
)) ))
conn.commit() db_connection.commit()
return user return 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 = ?', (user_id,)) cursor.execute('DELETE FROM Users WHERE user_id = %s', (user_id,))
conn.commit() db_connection.commit()
return {"message": "User deleted successfully"} return {"message": "User deleted successfully"}
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