Skip to content
Snippets Groups Projects
Commit 2f9c6f00 authored by Tiago Brito's avatar Tiago Brito
Browse files

Created get_products_by_category and search_products routes in product.py

parent 5edaf5e0
Branches
No related tags found
No related merge requests found
......@@ -60,6 +60,64 @@ def get_products(product_id):
cursor.close()
conn.close()
@product_bp.route('/products/category/<string:category_name>', methods=['GET'])
def get_products_by_category(category_name):
conn = db_connection()
cursor = conn.cursor(dictionary=True)
try:
cursor.execute("""
SELECT p.*, b.Name as BrandName, c.Name as CategoryName
FROM Product p
JOIN Category c ON p.CategoryID = c.CategoryID
JOIN Brand b ON p.BrandID = b.BrandID
WHERE c.Name = %s""", (category_name,))
products = cursor.fetchall()
return jsonify(products), 200
except Exception as e:
print(e)
return jsonify({'error': 'Database connection failed'}), 500
finally:
cursor.close()
conn.close()
# New route for searching products by name or brand
@product_bp.route('/products/search', methods=['GET'])
def search_products():
search_query = request.args.get('query', default="", type=str).strip()
selected_brand = request.args.get('brand', default="All Brands", type=str).strip()
if not search_query and selected_brand == "All Brands":
return jsonify({'message': 'No search criteria provided'}), 400
conn = db_connection()
if not conn:
return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor(dictionary=True)
try:
sql_query = """
SELECT p.*, b.Name AS BrandName, c.Name AS CategoryName
FROM Product p
JOIN Brand b ON p.BrandID = b.BrandID
JOIN Category c ON p.CategoryID = c.CategoryID
WHERE (p.Name LIKE %s OR b.Name LIKE %s)
"""
sql_params = ['%' + search_query + '%', '%' + search_query + '%']
# Filter by selected brand if not 'All Brands'
if selected_brand != "All Brands":
sql_query += " AND b.Name = %s"
sql_params.append(selected_brand)
cursor.execute(sql_query, sql_params)
products = cursor.fetchall()
return jsonify(products), 200
except Exception as e:
return jsonify({'error': 'Error processing your request', 'details': str(e)}), 500
finally:
cursor.close()
conn.close()
@product_bp.route('/products/<int:product_id>', methods=['PUT'])
def update_product(product_id):
data = request.json
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment