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

Fixed the duplication of user booking api and added rental scheduler

parent e33e6b07
No related branches found
No related tags found
No related merge requests found
import math
import random
import sqlite3
from datetime import datetime
from pathlib import Path
from apscheduler.schedulers.background import BackgroundScheduler
def insert_into_rentals(conn):
cursor = conn.cursor()
cursor.execute("""
SELECT user_id, bike_id, start_time, end_time
FROM Bookings
WHERE end_time IS NOT NULL
""")
rows = cursor.fetchall()
for row in rows:
user_id, bike_id, start_time, end_time = row
start_time = datetime.fromisoformat(start_time)
end_time = datetime.fromisoformat(end_time)
year = start_time.year
hour = start_time.hour
season = random.randint(1, 4)
holiday = random.randint(0, 1)
workingday = random.randint(0, 1)
weather = random.randint(1, 4)
temp = random.uniform(10, 35)
atemp = random.uniform(10, 35)
humidity = random.uniform(20, 100)
windspeed = random.uniform(0, 50)
count = random.randint(0, 100)
cursor.execute("""
INSERT INTO rentals (
user_id, bike_id, year, hour,
season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
user_id, bike_id, year, hour,
season, holiday, workingday, weather, temp, atemp, humidity, windspeed, count
))
conn.commit()
def scheduled_job():
print("Running scheduled job...")
parent_directory = Path(__file__).resolve().parent.parent
db_file_path = parent_directory / "microservices" / "my_ride.db"
print(f"Using database at: {db_file_path}") # For debugging
with sqlite3.connect(db_file_path, check_same_thread=False) as conn:
try:
insert_into_rentals(conn)
print("Data has been successfully inserted into rentals.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
scheduler = BackgroundScheduler()
scheduler.add_job(scheduled_job, 'interval', hours=1)
scheduler.start()
print("Press Ctrl+{0} to exit".format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
pass
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
if __name__ == "__main__":
main()
...@@ -95,15 +95,15 @@ async def get_booking(booking_id: int): ...@@ -95,15 +95,15 @@ async def get_booking(booking_id: int):
@app.post("/bookings/") @app.post("/bookings/")
async def book_bike(booking: Booking): async def book_bike(booking: Booking):
# Check for existing active booking # Check for existing active booking for the user_id or bike_id
cursor.execute(""" cursor.execute("""
SELECT 1 FROM Bookings SELECT 1 FROM Bookings
WHERE user_id = ? AND bike_id = ? AND payment_state = 'Booked' WHERE (user_id = ? OR bike_id = ?) AND payment_state = 'Booked'
""", (booking.user_id, booking.bike_id)) """, (booking.user_id, booking.bike_id))
existing_booking = cursor.fetchone() existing_booking = cursor.fetchone()
if existing_booking: if existing_booking:
raise HTTPException(status_code=400, detail="Already Booked: This bike is currently booked.") raise HTTPException(status_code=400, detail="Already Booked")
# Fetch user details # Fetch user details
cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = ?", (booking.user_id,)) cursor.execute("SELECT wallet_balance FROM Users WHERE user_id = ?", (booking.user_id,))
......
No preview for this file type
from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
import sqlite3
from pydantic import BaseModel
from typing import List
import sqlite3
from datetime import datetime
import math
def insert_into_rentals():
conn = sqlite3.connect("my_ride.db")
cursor = conn.cursor()
# Assume that this function is called right after a booking update where end_time is set
cursor.execute("""
SELECT user_id, bike_id, start_time, end_time
FROM Bookings
WHERE end_time IS NOT NULL
""")
rows = cursor.fetchall()
for row in rows:
user_id, bike_id, start_time, end_time = row
start_time = datetime.fromisoformat(start_time)
end_time = datetime.fromisoformat(end_time)
duration_hours = math.ceil((end_time - start_time).total_seconds() / 3600)
duration_hours = max(1, duration_hours) # Ensure minimum of 1 hour
year = start_time.year
hour = start_time.hour
cursor.execute("""
INSERT INTO rentals (user_id, bike_id, year, hour, duration_hours)
VALUES (?, ?, ?, ?, ?)
""", (user_id, bike_id, year, hour, duration_hours))
conn.commit()
conn.close()
\ No newline at end of file
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