Skip to content

Commit

Permalink
Complete API/TEST
Browse files Browse the repository at this point in the history
  • Loading branch information
eoa21004 committed Nov 8, 2024
1 parent 88cd05d commit 8994786
Show file tree
Hide file tree
Showing 10 changed files with 280 additions and 106 deletions.
30 changes: 0 additions & 30 deletions Backend/Dockerfile

This file was deleted.

78 changes: 64 additions & 14 deletions Backend/main.py → Backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@
This module provides functions for HTTP communication and
route functions
"""
import sqlite3
import databasefunctions
from flask import Flask, request, jsonify
from petfuc import get_random_pet
from userfuc import add_user_faviorte, remove_user_faviorte, replace_user_location
from database_files import databasefunctions
app = Flask(__name__)

# -----------------------------------------------------------------------------------------
Expand All @@ -17,9 +14,11 @@ def add_newuser():
Adds new user to database
"""
data = request.get_json()
newuser_id = databasefunctions.insert_user(data.get("name"), data.get("age"), data.get("location"))
newuser_id = databasefunctions.insert_user(data.get("username"),data.get("password"),
data.get("name"), data.get("age"),
data.get("location"))

return jsonify({'user_id': newuser_id}), 200
return jsonify({'user_id': newuser_id}), 200

@app.route("/add_newpet", methods=["POST"])
def add_newpet():
Expand All @@ -28,21 +27,29 @@ def add_newpet():
"""
data = request.get_json()
newpet_id = databasefunctions.insert_pet(data.get("name"), data.get("age"),
data.get("gender"), data.get("breed"), data.get("type"),
data.get("gender"), data.get("breed"), data.get("type"),
data.get("location"), data.get("photo_path"))

return jsonify({'pet_id': newpet_id}), 200
return jsonify({'pet_id': newpet_id}), 200


@app.route("/add_newfavorite", methods=["POST"])
def add_newfavorite():
"""
Adds new user favorite to database
INSERT INTO pets (name, age, gender, breed, type, location, photo_path)
VALUES
('Bella', 3, 'female', 'Golden Retriever', 'dog', 'New York', 'images/Chuck.jpg'),
('Max', 5, 'male', 'Maine Coon', 'cat', 'Boston', 'images/gunner.jpg'),
('Luna', 2, 'female', 'Siamese', 'cat', 'Chicago', 'images/luna.jpg'),
('Charlie', 4, 'male', 'Beagle', 'dog', 'Los Angeles', 'images/lizzie_izzie.jpg'),
('Daisy', 1, 'female', 'Labrador Retriever', 'dog', 'Miami', 'images/monster.jpg');
"""
data = request.get_json()
newfavorite_id = databasefunctions.insert_favorite(data.get("user_id"), data.get("pet_id"))

return jsonify({'faviorte_id': newfavorite_id}), 200
return jsonify({'faviorte_id': newfavorite_id}), 200



Expand All @@ -66,7 +73,7 @@ def removepet():
Remove pet from database
"""
data = request.get_json()
petid = data.get("petid")
petid = data.get("pet_id")
roweffected = databasefunctions.remove_pet(petid)

return (f"{roweffected}, row was deleted in pet table"), 200
Expand All @@ -85,6 +92,25 @@ def removefavorite():
# ---------------------------------------------------------------------



@app.route("/fetch_userid", methods=["POST"])
def fetch_userid():
"""
fetch userid associated with username and password
"""
data = request.get_json()
username = data.get("username")
password = data.get("password")


userid = databasefunctions.fetch_userid_from_username_and_password(username, password)

return jsonify(userid), 200





@app.route("/fetch_pet", methods=["POST"])
def fetch_pet():
"""
Expand All @@ -94,7 +120,7 @@ def fetch_pet():
petid = data.get("pet_id")
users_row = databasefunctions.fetch_pet_by_id(petid)

return jsonify(users_row), 200
return jsonify(users_row), 200


@app.route("/fetch_user", methods=["POST"])
Expand All @@ -106,7 +132,7 @@ def fetch_user():
userid = data.get("user_id")
users_row = databasefunctions.fetch_user_by_id(userid)

return jsonify(users_row), 200
return jsonify(users_row), 200


@app.route("/fetch_favorited_pets", methods=["POST"])
Expand All @@ -118,11 +144,35 @@ def fetch_favorite_pet():
userid = data.get("user_id")
favorited_pets = databasefunctions.fetch_favorites_by_user(userid)

return jsonify(favorited_pets), 200
return jsonify(favorited_pets), 200


# ---------------------------------------------------------------

@app.route("/fetch_allusers", methods=["POST"])
def fetch_allusers():
"""
fetches all users in database
"""

allusers = databasefunctions.fetch_all_users()
return jsonify(allusers), 200


@app.route("/fetch_allpets", methods=["POST"])
def fetch_allpets():
"""
fetches all pets in database
"""

allpets = databasefunctions.fetch_all_pets()
return jsonify(allpets), 200







if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
app.run(host="0.0.0.0", debug=True)
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
'''DATABASE FUNCTIONS'''
from contextlib import closing
import sqlite3

def connect_db():
"""Establish a connection to the SQLite database."""
return sqlite3.connect('Projectdatabase.db') #this might change
return sqlite3.connect('projectdatabase.db') #this might change

# ---------------------------------------------------------------------------------------------- insert functions
# --------------------- insert functions

def insert_user(name, age, location):
def insert_user(username, password, name, age, location):
"""Insert a new user into the accounts table."""
with closing(connect_db()) as conn, conn:
cursor = conn.cursor()
cursor.execute(
'''INSERT INTO accounts (name, age, location)
VALUES (?, ?, ?)''',
(name, age, location)
'''INSERT INTO accounts (username, password, name, age, location)
VALUES (?, ?, ?, ?, ?)''',
(username, password, name, age, location)
)
conn.commit()
return cursor.lastrowid
Expand Down Expand Up @@ -45,7 +46,7 @@ def insert_favorite(user_id, pet_id):
conn.commit()
return cursor.lastrowid

# ------------------------------------------------------------------------------------- remove functions
# ---------------------------remove functions

def remove_user(user_id):
"""Remove a pet from the accounts table."""
Expand Down Expand Up @@ -77,79 +78,99 @@ def remove_favorite(user_id, pet_id):
"""Remove a favorite row from the favorites table based on user_id and pet_id."""
with closing(connect_db()) as conn:
cursor = conn.cursor()
# Execute DELETE query to remove the row matching user_id and pet_id

# Execute DELETE query to remove the row matching user_id and pet_id
cursor.execute("""
DELETE FROM favorites
WHERE user_id = ? AND pet_id = ?
""", (user_id, pet_id))

conn.commit()
return cursor.rowcount # Returns the number of rows affected (should be 1 if successful)

# ----------------------------------------------------------------------------------------------------------- change fucntions
# ------------------------------------------- change fucntions


def change_user_attributes(user_id, attribute, change):
"""Update a user's attribute in the accounts table."""

# List of valid column names to avoid SQL injection
valid_columns = ['name', 'age', 'location'] # Add your valid column names here
valid_columns = ['name', 'age', 'location', 'password'] # Add your valid column names here

if attribute not in valid_columns:
raise ValueError("Invalid attribute name.")

with closing(connect_db()) as conn:
cursor = conn.cursor()

# Use the attribute directly, now it's safe since we validated it
cursor.execute(f"""
UPDATE accounts
SET {attribute} = ?
WHERE user_id = ?
""", (change, user_id))

conn.commit()
return fetch_user_by_id(user_id)


def change_pet_attributes(pet_id, attribute, change):
"""Update a user's attribute in the accounts table."""

# List of valid column names to avoid SQL injection
valid_columns = ['name', 'age', 'location', 'breed', 'gender', 'type', 'photo_path'] # Add your valid column names here

valid_columns = ['name', 'age', 'location', 'breed',
'gender', 'type', 'photo_path'] # Add your valid column names here

if attribute not in valid_columns:
raise ValueError("Invalid attribute name.")

with closing(connect_db()) as conn:
cursor = conn.cursor()

# Use the attribute directly, now it's safe since we validated it
cursor.execute(f"""
UPDATE pets
SET {attribute} = ?
WHERE pet_id = ?
""", (change, pet_id))

conn.commit()
return fetch_pet_by_id(pet_id)

# ----------------------------------------------------------------------------------------------------------- fetch functions
# ------------------------------------- fetch functions


def fetch_userid_from_username_and_password(username,password):
"""Get a users ID from there username and password"""

with closing(connect_db()) as conn:
cursor = conn.cursor()

# Execute DELETE query to remove the row matching user_id and pet_id
cursor.execute("""
SELECT user_id FROM accounts
WHERE username = ? AND password = ?
""", (username, password))

result = cursor.fetchone()
if result:
return result[0]
else:
return None


def fetch_favorites_by_user(user_id):
"""Fetch all favorite pets for a given user_id."""
with closing(connect_db()) as conn:
cursor = conn.cursor()

cursor.execute("""
SELECT pets.*
FROM pets
INNER JOIN favorites ON pets.pet_id = favorites.pet_id
WHERE favorites.user_id = ?
""", (user_id,))

return cursor.fetchall()


Expand Down
Loading

0 comments on commit 8994786

Please sign in to comment.