Refactor database interactions to use SQLAlchemy ORM; update user and token management in api_security.py and user.py; add models for Items, Tokens, and User

This commit is contained in:
Mabe
2026-09-23 19:54:20 -07:00
parent c0108fd1e1
commit cfe8a0e22d
6 changed files with 132 additions and 163 deletions
+73 -98
View File
@@ -1,7 +1,10 @@
import mariadb
import logging
from dotenv import load_dotenv
import os
from models import Items
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus
#Logging
@@ -17,102 +20,6 @@ try:
except Exception as e:
logging.exception('An error occurred')
def connect(db_user, db_psswd, db_host, db_port, db_name):
try:
global connection
connection = mariadb.connect(user=db_user,
password=db_psswd,
host=db_host,
port=db_port,
database=db_name)
print("Connected to MariaDB successfully!")
logging.info("Connected to MariaDB successfully!")
except mariadb.Error as e:
print(f"Error connecting to DB: {e}")
logging.error("Error connecting")
logging.debug(f"Error connecting to DB: {e}")
def new_part(cloth_type, weight, pieces):
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "INSERT INTO luggage (clothes, weight, pieces) VALUES (?, ?, ?)"
executed_data = (cloth_type, weight, pieces)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("new Insert is in DB")
def fetch_clothes():
cursor = connection.cursor()
cursor.execute("SELECT clothes FROM luggage")
clothes = [str(row[0]) for row in cursor.fetchall()]
logging.info("fetched clothes")
return clothes
def update_weight(cloth_type, weight):
cursor = connection.cursor()
executed = "UPDATE luggage SET weight = ? WHERE clothes = ?"
executed_data = (weight, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "UPDATE luggage SET pieces = ? WHERE clothes = ?"
executed_data = (pieces, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("pieces updated")
def fetch_weight(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT weight FROM luggage WHERE clothes = ?", (cloth_type,))
weight = cursor.fetchone()[0]
logging.info("fetched weight")
return weight
def fetch_luggage_weight():
cursor = connection.cursor()
cursor.execute("SELECT sum(weight) FROM luggage")
weight = cursor.fetchone()[0]
logging.info("fetched luggage weight")
return weight
def fetch_piece(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT pieces FROM luggage WHERE clothes = ?", (cloth_type,))
pieces = cursor.fetchone()[0]
logging.info("fetched luggage pieces")
return pieces
def fetch_all_pieces():
cursor = connection.cursor()
cursor.execute("SELECT sum(pieces) FROM luggage")
pieces = cursor.fetchone()[0]
logging.info("fetched all luggage pieces")
return pieces
def delete(cloth_type):
cursor = connection.cursor()
cursor.execute("DELETE FROM luggage WHERE clothes = ?;", (cloth_type,))
logging.critical(f"{cloth_type} was deleted")
connection.commit()
def check_clothe(clothe_type):
cursor = connection.cursor()
cursor.execute("SELECT (SELECT clothes FROM luggage WHERE clothes = ? LIMIT 1) AS clothes", (clothe_type,))
check = cursor.fetchone()[0]
return check
#using .env
load_dotenv()
db_name = os.getenv("DB_NAME")
@@ -123,4 +30,72 @@ db_host = os.getenv("DB_HOST")
if db_host == None:
logging.error("no hostname provided")
os._exit(1)
connect(db_user, db_psswd, db_host, int(db_port), db_name)
engine = create_engine(f"mariadb+mariadbconnector://{db_user}:{quote_plus(db_psswd)}@{db_host}:{db_port}/{db_name}")
Session = sessionmaker(bind=engine)
session = Session()
def new_part(cloth_type, weight, pieces):
existing = session.query(Items).filter_by(clothes=cloth_type).first()
if existing:
logging.debug("Item already inserted")
else:
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
new_item = Items(clothes=cloth_type, weight=weight, pieces=pieces)
session.add(new_item)
session.commit()
logging.info("new Insert is in DB")
def update_weight(cloth_type, weight):
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.weight = weight
session.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.pieces = pieces
session.commit()
logging.info("pieces updated")
def delete(cloth_type):
logging.critical(f"{cloth_type} was deleted")
session.query(Items).filter_by(clothes=cloth_type).delete()
session.commit()
def fetch_clothes():
logging.info("fetched clothes")
return [row[0] for row in session.query(Items.clothes).all()]
def fetch_weight(cloth_type):
logging.info("fetched weight")
result = session.query(Items.weight).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_luggage_weight():
logging.info("fetched whole weight")
result = session.query(func.sum(Items.weight)).scalar()
return result if result else None
def fetch_piece(cloth_type):
logging.info("fetched pieces")
result = session.query(Items.pieces).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_all_pieces():
logging.info("fetched all pieces")
result = session.query(Items.pieces).all()
return [row[0] for row in session.query(Items.pieces).all()]
def check_clothe(clothe_type):
exists = session.query(Items.clothes).filter_by(clothes=clothe_type).first() is not None
return exists