ARTICLE AD BOX
Could someone help me design code for a shopping page and working cart.
# Import Flask tools for routes, templates, JSON, redirects, and URL building from flask import Flask, render_template, jsonify, redirect, url_for # Import sqlite3 to work with the SQLite database directly import sqlite3 # Create the Flask app app = Flask(__name__) # Database file name DATABASE = "shopping.db" # ----------------------------- # DATABASE CONNECTION FUNCTION # ----------------------------- def get_db_connection(): # Connect to the SQLite database file conn = sqlite3.connect(DATABASE) # Let rows behave like dictionaries conn.row_factory = sqlite3.Row # Return the connection return conn # ----------------------------- # CREATE DATABASE TABLES # ----------------------------- def init_db(): # Open database connection conn = get_db_connection() cursor = conn.cursor() # Create the products table cursor.execute(""" CREATE TABLE IF NOT EXISTS product_item ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, descr TEXT, price REAL NOT NULL, img TEXT UNIQUE ) """) # Create the cart table # Each row means one unit of a product in the cart cursor.execute(""" CREATE TABLE IF NOT EXISTS cart_item ( id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER, FOREIGN KEY (product_id) REFERENCES product_item (id) ) """) # Save changes conn.commit() # Close connection conn.close() # ----------------------------- # ADD SAMPLE PRODUCTS # ----------------------------- def seed_products(): # Open connection conn = get_db_connection() cursor = conn.cursor() # Count how many products are already stored existing_products = cursor.execute( "SELECT COUNT(*) FROM product_item" ).fetchone()[0] # Only seed if the table is empty if existing_products == 0: cursor.execute( "INSERT INTO product_item (name, descr, price, img) VALUES (?, ?, ?, ?)", ("Apple", "Fresh red apple", 1.99, "apple.jpg") ) cursor.execute( "INSERT INTO product_item (name, descr, price, img) VALUES (?, ?, ?, ?)", ("Banana", "Sweet yellow banana", 0.99, "banana.jpg") ) cursor.execute( "INSERT INTO product_item (name, descr, price, img) VALUES (?, ?, ?, ?)", ("Orange", "Juicy orange", 1.49, "orange.jpg") ) # Save changes conn.commit() # Close connection conn.close() # ----------------------------- # HOME PAGE ROUTE # ----------------------------- @app.route("/") def index(): # Open connection conn = get_db_connection() # Fetch all products products = conn.execute("SELECT * FROM product_item").fetchall() # Close connection conn.close() # Send products to the home template return render_template("home.html", products=products) # ----------------------------- # ADD TO CART ROUTE # ----------------------------- @app.route("/cart/add/<int:product_id>", methods=["POST"]) def add_to_cart(product_id): # Open connection conn = get_db_connection() cursor = conn.cursor() # Insert one row into cart_item for this product cursor.execute( "INSERT INTO cart_item (product_id) VALUES (?)", (product_id,) ) # Save the change conn.commit() # Close connection conn.close() # Return JSON response return jsonify({"message": "Item added to cart"}) # ----------------------------- # CART PAGE ROUTE # ----------------------------- @app.route("/cart") def cart(): # Open connection conn = get_db_connection() # Group cart items by product so duplicates appear as one line cart_items = conn.execute(""" SELECT product_item.id AS product_id, product_item.name, product_item.price, product_item.img, COUNT(cart_item.id) AS quantity, SUM(product_item.price) AS subtotal FROM cart_item JOIN product_item ON cart_item.product_id = product_item.id GROUP BY product_item.id, product_item.name, product_item.price, product_item.img """).fetchall() # Calculate overall total total_price = conn.execute(""" SELECT COALESCE(SUM(product_item.price), 0) AS total FROM cart_item JOIN product_item ON cart_item.product_id = product_item.id """).fetchone()["total"] # Close connection conn.close() # Render the cart page return render_template( "cart.html", cart_items=cart_items, total_price=total_price ) # ----------------------------- # DECREASE QUANTITY BY 1 # ----------------------------- @app.route("/cart/decrease/<int:product_id>", methods=["POST"]) def decrease_quantity(product_id): # Open connection conn = get_db_connection() cursor = conn.cursor() # Find one cart row for this product cart_row = cursor.execute(""" SELECT id FROM cart_item WHERE product_id = ? LIMIT 1 """, (product_id,)).fetchone() # If found, delete one row if cart_row: cursor.execute( "DELETE FROM cart_item WHERE id = ?", (cart_row["id"],) ) conn.commit() # Close connection conn.close() # Go back to cart page return redirect(url_for("cart")) # ----------------------------- # INCREASE QUANTITY BY 1 # ----------------------------- @app.route("/cart/increase/<int:product_id>", methods=["POST"]) def increase_quantity(product_id): # Open connection conn = get_db_connection() cursor = conn.cursor() # Add one more of this product to the cart cursor.execute( "INSERT INTO cart_item (product_id) VALUES (?)", (product_id,) ) # Save change conn.commit() # Close connection conn.close() # Go back to cart page return redirect(url_for("cart")) # ----------------------------- # REMOVE ALL OF ONE PRODUCT # ----------------------------- @app.route("/cart/remove_all/<int:product_id>", methods=["POST"]) def remove_all_of_item(product_id): # Open connection conn = get_db_connection() cursor = conn.cursor() # Delete every row for this product from the cart cursor.execute( "DELETE FROM cart_item WHERE product_id = ?", (product_id,) ) # Save change conn.commit() # Close connection conn.close() # Go back to cart page return redirect(url_for("cart")) # ----------------------------- # CLEAR ENTIRE CART # ----------------------------- @app.route("/cart/clear", methods=["POST"]) def clear_cart(): # Open connection conn = get_db_connection() cursor = conn.cursor() # Delete all rows from the cart table cursor.execute("DELETE FROM cart_item") # Save change conn.commit() # Close connection conn.close() # Go back to cart page return redirect(url_for("cart")) # ----------------------------- # OPTIONAL JSON CART VIEW # ----------------------------- @app.route("/view_cart") def view_cart(): # Open connection conn = get_db_connection() # Get grouped cart items and quantities cart_items = conn.execute(""" SELECT product_item.name, product_item.price, COUNT(cart_item.id) AS quantity FROM cart_item JOIN product_item ON cart_item.product_id = product_item.id GROUP BY product_item.id, product_item.name, product_item.price """).fetchall() # Get overall total total_price = conn.execute(""" SELECT COALESCE(SUM(product_item.price), 0) AS total FROM cart_item JOIN product_item ON cart_item.product_id = product_item.id """).fetchone()["total"] # Close connection conn.close() # Build a simple dictionary for JSON cart_contents = {} for item in cart_items: cart_contents[item["name"]] = item["quantity"] # Return JSON response return jsonify({ "cart_contents": cart_contents, "total_price": total_price }) # ----------------------------- # RUN THE APP # ----------------------------- if __name__ == "__main__": # Create the tables if needed init_db() # Add starter products if needed seed_products() # Run the app app.run(debug=True) #if you need the cart page <!DOCTYPE html> <html> <head> <title>Your Cart</title> </head> <body> <h1>Your Cart</h1> <!-- Link back to the shopping page --> <p><a href="{{ url_for('index') }}">Back to Shop</a></p> {% if cart_items %} <!-- Clear the entire cart --> <form action="{{ url_for('clear_cart') }}" method="POST"> <button type="submit">Clear Cart</button> </form> <hr> {% for item in cart_items %} <div class="cart-item"> <h3>{{ item.name }}</h3> <!-- Product image --> <img src="{{ url_for('static', filename=item.img) }}" alt="{{ item.name }}" width="150" height="150"> <!-- Price for one unit --> <p>Price: £{{ item.price }}</p> <!-- Current quantity --> <p>Quantity: {{ item.quantity }}</p> <!-- Total for this product --> <p>Subtotal: £{{ item.subtotal }}</p> <!-- Increase quantity --> <form action="{{ url_for('increase_quantity', product_id=item.product_id) }}" method="POST" style="display:inline;"> <button type="submit">+</button> </form> <!-- Decrease quantity --> <form action="{{ url_for('decrease_quantity', product_id=item.product_id) }}" method="POST" style="display:inline;"> <button type="submit">-</button> </form> <!-- Remove all of this product --> <form action="{{ url_for('remove_all_of_item', product_id=item.product_id) }}" method="POST" style="display:inline;"> <button type="submit">Remove All</button> </form> </div> <hr> {% endfor %} <h2>Total: £{{ total_price }}</h2> {% else %} <p>Your cart is empty.</p> {% endif %} </body> </html> #home page as well to display the products <!DOCTYPE html> <html> <head> <title>Shopping Page</title> </head> <body> <h1>Shopping Page</h1> <!-- Link to cart page --> <p><a href="{{ url_for('cart') }}">Go to Cart</a></p> <!-- Loop through products from the database --> {% for product in products %} <div class="product-item"> <h3>{{ product.name }}</h3> <!-- Loads image from static folder --> <img src="{{ url_for('static', filename=product.img) }}" alt="{{ product.name }}" width="200" height="200"> <p>{{ product.descr }}</p> <p>£{{ product.price }}</p> <!-- Button sends product id to Flask --> <button onclick="addToCart({{ product.id }})" type="button">Add to Cart</button> </div> <hr> {% endfor %} <script> // Function that runs when "Add to Cart" button is clicked function addToCart(productId) { // productId is passed from the button (e.g. 1, 2, 3) // Send a request to the Flask backend fetch(`/cart/add/${productId}`, { // Calls URL like /cart/add/1 method: "POST" // Tells Flask we are sending data (matches POST route) }) // Take the response from Flask and convert it to JSON .then(response => response.json()) // Converts response into usable JavaScript object // Use the data returned from Flask .then(data => { alert(data.message); // Shows popup: "Item added to cart" }) // If something goes wrong, log the error in the browser console .catch(error => console.error("Error:", error)); // Helps with debugging } </script> </body> </html>
