Skip to content
Snippets Groups Projects

updated code for sommon database

parent b0ba87d3
No related branches found
No related tags found
No related merge requests found
No preview for this file type
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from typing import List from fastapi.middleware.cors import CORSMiddleware
import sqlite3 import sqlite3
from pathlib import Path
from typing import Optional, Tuple, List
app = FastAPI() 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
# SQLite connection # SQLite connection
conn = sqlite3.connect('bikes.db') 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() cursor = conn.cursor()
# Create the Admins table if it doesn't exist # Create the Admins table if it doesn't exist
...@@ -23,15 +39,26 @@ conn.commit() ...@@ -23,15 +39,26 @@ conn.commit()
# Admin model # Admin model
# class Admin(BaseModel):
# username: str
# password: str
# email: str
# phone_number: str
class Admin(BaseModel): class Admin(BaseModel):
username: str username: str
password: str password: Optional[str]
email: str
phone_number: str
class AdminResponse(BaseModel):
username: str
email: str email: str
phone_number: str phone_number: str
# Routes # Routes
@app.post("/admins/", response_model=Admin) @app.post("/admins/", response_model=AdminResponse)
async def create_admin(admin: Admin): async def create_admin(admin: Admin):
cursor.execute(''' cursor.execute('''
INSERT INTO Admins INSERT INTO Admins
...@@ -41,21 +68,19 @@ async def create_admin(admin: Admin): ...@@ -41,21 +68,19 @@ async def create_admin(admin: Admin):
admin.username, admin.password, admin.email, admin.phone_number admin.username, admin.password, admin.email, admin.phone_number
)) ))
conn.commit() conn.commit()
return admin return AdminResponse(
username=admin.username,
email=admin.email,
phone_number=admin.phone_number
)
# @app.get("/admins/", response_model=List[Admin])
# async def read_admins():
# cursor.execute('SELECT * FROM Admins')
# admins = cursor.fetchall()
# return admins
@app.get("/admins/", response_model=List[Admin]) @app.get("/admins/", response_model=List[AdminResponse])
async def read_admins(): async def read_admins():
cursor.execute('SELECT username, email, phone_number FROM Admins') cursor.execute('SELECT username, email, phone_number FROM Admins')
admins_data: List[Tuple[str, str, str]] = cursor.fetchall() admins_data: List[Tuple[str, str, str]] = cursor.fetchall()
admins = [ admins = [
Admin( AdminResponse(
username=admin[0], username=admin[0],
email=admin[1], email=admin[1],
phone_number=admin[2] phone_number=admin[2]
...@@ -63,7 +88,6 @@ async def read_admins(): ...@@ -63,7 +88,6 @@ async def read_admins():
] ]
return admins return admins
@app.get("/admins/{admin_id}", response_model=Admin) @app.get("/admins/{admin_id}", response_model=Admin)
async def read_admin(admin_id: int): async def read_admin(admin_id: int):
cursor.execute('SELECT * FROM Admins WHERE admin_id = ?', (admin_id,)) cursor.execute('SELECT * FROM Admins WHERE admin_id = ?', (admin_id,))
......
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 typing import List from typing import List
import sqlite3 import sqlite3
from pathlib import Path
from typing import Optional
app = FastAPI() 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 # SQLite connection
conn = sqlite3.connect('bikes.db') # 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"
# print(db_file_path)
conn = sqlite3.connect(db_file_path)
cursor = conn.cursor() cursor = conn.cursor()
# Create the Bikes table if it doesn't exist # Create the Bikes table if it doesn't exist
...@@ -28,14 +49,12 @@ conn.commit() ...@@ -28,14 +49,12 @@ conn.commit()
# Bike model # Bike model
class Bike(BaseModel): class Bike(BaseModel):
model: str model: str
status: str status: Optional[str]
location: str location: str
condition: str condition: str
price_per_hour: float price_per_hour: float
last_maintenance_date: str last_maintenance_date: str
maintenance_history: str maintenance_history: str
# Routes # Routes
@app.post("/bikes/", response_model=Bike) @app.post("/bikes/", response_model=Bike)
...@@ -52,6 +71,7 @@ async def create_bike(bike: Bike): ...@@ -52,6 +71,7 @@ async def create_bike(bike: Bike):
return bike return bike
@app.get("/bikes/", response_model=List[Bike]) @app.get("/bikes/", response_model=List[Bike])
async def read_bikes(): async def read_bikes():
cursor.execute('SELECT * FROM Bikes') cursor.execute('SELECT * FROM Bikes')
...@@ -59,15 +79,17 @@ async def read_bikes(): ...@@ -59,15 +79,17 @@ async def read_bikes():
bike_objects = [] bike_objects = []
for bike in bikes: for bike in bikes:
bike_obj = Bike( bike_obj = Bike(
brand=bike[0],
model=bike[1], model=bike[1],
year=bike[2], status=bike[2],
price=bike[3] 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) bike_objects.append(bike_obj)
return bike_objects return bike_objects
@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 = ?', (bike_id,))
......
File added
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 typing import List from typing import List
import sqlite3 import sqlite3
from pathlib import Path
from typing import Optional
from fastapi import HTTPException
app = FastAPI() 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 # SQLite connection
conn = sqlite3.connect('rentals.db') 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() cursor = conn.cursor()
# Create the Rentals table if it doesn't exist # Create the Rentals table if it doesn't exist
...@@ -36,7 +54,6 @@ conn.commit() ...@@ -36,7 +54,6 @@ conn.commit()
# Rental model # Rental model
class Rental(BaseModel): class Rental(BaseModel):
id: int
user_id: int user_id: int
bike_id: int bike_id: int
year: int year: int
...@@ -52,20 +69,88 @@ class Rental(BaseModel): ...@@ -52,20 +69,88 @@ class Rental(BaseModel):
count: int count: int
# Routes # # Routes
# @app.post("/rentals/", response_model=Rental)
# async def create_rental(rental: Rental):
# 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()
# return rental
# @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()
# return rental
# except Exception as e:
# # Log the exception
# print(f"Error creating rental: {e}")
# # Raise an HTTPException with status code 422 and error message
# raise HTTPException(status_code=422, detail=str(e))
# @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()
# return rental
# except Exception as e:
# # Log the exception
# print(f"Error creating rental: {e}")
# # Raise an HTTPException with status code 422 and error message
# raise HTTPException(status_code=422, detail=str(e))
@app.post("/rentals/", response_model=Rental) @app.post("/rentals/", response_model=Rental)
async def create_rental(rental: Rental): async def create_rental(rental: Rental):
cursor.execute(''' try:
INSERT INTO Rentals cursor.execute('''
(id, user_id, bike_id, year, hour, season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count) INSERT INTO Rentals
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) (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.user_id, rental.bike_id, rental.year, rental.hour,
rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count rental.season, rental.holiday, rental.workingday, rental.weather,
)) rental.temp, rental.atemp, rental.humidity, rental.windspeed, rental.count
conn.commit() ))
return rental 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:
# Log the exception
print(f"Error creating rental: {e}")
# Raise an HTTPException with status code 422 and error message
raise HTTPException(status_code=422, detail=str(e))
@app.get("/rentals/", response_model=List[Rental]) @app.get("/rentals/", response_model=List[Rental])
...@@ -73,9 +158,25 @@ async def read_rentals(): ...@@ -73,9 +158,25 @@ async def read_rentals():
cursor.execute('SELECT * FROM Rentals') cursor.execute('SELECT * FROM Rentals')
rentals = cursor.fetchall() rentals = cursor.fetchall()
rental_objects = [] 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: for rental in rentals:
rental_objects.append(Rental( rental_objects.append(Rental(
id=rental[0],
user_id=rental[1], user_id=rental[1],
bike_id=rental[2], bike_id=rental[2],
year=rental[3], year=rental[3],
......
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 typing import List from typing import List
import sqlite3 import sqlite3
from pathlib import Path
from typing import Optional
app = FastAPI() 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 # SQLite connection
conn = sqlite3.connect('review.db') 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() cursor = conn.cursor()
# Create the Reviews table if it doesn't exist # Create the Reviews table if it doesn't exist
......
...@@ -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
from pathlib import Path
from typing import Optional from typing import Optional
app = FastAPI() app = FastAPI()
...@@ -17,7 +18,11 @@ app.add_middleware( ...@@ -17,7 +18,11 @@ app.add_middleware(
) )
# SQLite connection # SQLite connection
conn = sqlite3.connect('bikes.db') 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() cursor = conn.cursor()
# Create the Users table if it doesn't exist # Create the Users table if it doesn't exist
...@@ -38,7 +43,7 @@ conn.commit() ...@@ -38,7 +43,7 @@ conn.commit()
class User(BaseModel): class User(BaseModel):
username: str username: str
password: str password: str
email: str email: str
phone_number: str phone_number: str
credit_card_info: Optional[str] = None credit_card_info: Optional[str] = None
......
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