Python Programming: Building a Shopping Cart App with Flask

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating Flask Application
  5. Creating Routes
  6. Implementing Shopping Cart
  7. Testing the Application
  8. Conclusion

Introduction

In this tutorial, we will learn how to build a shopping cart application using Python and Flask framework. The shopping cart will allow users to select and add items to their cart, view the cart contents, and proceed to checkout. By the end of this tutorial, you will have a basic understanding of how to create a functional shopping cart application.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. You should also have the following software installed on your system:

  • Python 3
  • Flask

Setup

To begin, let’s set up our development environment. Follow these steps:

  1. Create a new directory for your project.

  2. Open a terminal or command prompt and navigate to the project directory.

  3. Create a virtual environment to isolate the project dependencies:
    python3 -m venv venv
    
  4. Activate the virtual environment:
    • On macOS and Linux:
      source venv/bin/activate
      
    • On Windows:
      venv\Scripts\activate
      
  5. Install Flask using pip:
    pip install Flask
    

    With the setup complete, we are ready to start building our shopping cart application.

Creating Flask Application

  1. Create a new file called app.py in your project directory.

  2. Import the necessary modules:
    from flask import Flask, render_template
    
  3. Create a Flask application instance:
    app = Flask(__name__)
    
  4. Create a root route that will display the home page:
    @app.route('/')
    def home():
        return render_template('index.html')
    
  5. Run the Flask application:
    if __name__ == '__main__':
        app.run()
    

    Creating Routes

Now, let’s create the routes for our shopping cart application.

  1. Create a new template file called index.html in a folder named templates.

  2. Add the following HTML code to the index.html template:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Shopping Cart</title>
    </head>
    <body>
        <h1>Welcome to the Shopping Cart</h1>
    </body>
    </html>
    
  3. Add routes for viewing products, adding them to the cart, and viewing the cart. Modify the app.py file as follows:
    @app.route('/products')
    def products():
        # Fetch the list of products from the database or a data source
        products = [
            {'id': 1, 'name': 'Product 1', 'price': 10.99},
            {'id': 2, 'name': 'Product 2', 'price': 19.99},
            {'id': 3, 'name': 'Product 3', 'price': 8.99}
        ]
    
        return render_template('products.html', products=products)
    
    @app.route('/add-to-cart/<int:product_id>')
    def add_to_cart(product_id):
        # Add the selected product to the user's cart
        # Implementation code here
        return 'Product added to cart: {}'.format(product_id)
    
    @app.route('/cart')
    def view_cart():
        # Fetch the user's cart from the database or a data source
        # Implementation code here
        return render_template('cart.html')
    

    Implementing Shopping Cart

Now, let’s implement the shopping cart functionality.

  1. Create a new template file called products.html in the templates folder.

  2. Add the following HTML code to the products.html template:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Products</title>
    </head>
    <body>
        <h1>Available Products</h1>
        <ul>
               
        </ul>
    </body>
    </html>
    
  3. Create a new template file called cart.html in the templates folder.

  4. Add the following HTML code to the cart.html template:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Cart</title>
    </head>
    <body>
        <h1>Shopping Cart</h1>
        <p>Your cart is empty.</p>
    </body>
    </html>
    

    Testing the Application

  5. Start the Flask application by running the following command in the terminal:
    python app.py
    
  6. Open a web browser and visit http://localhost:5000 to see the home page.

  7. Click on the “Available Products” link to view the products.

  8. Click on the “Add to Cart” link for a product to add it to the cart.

  9. Visit http://localhost:5000/cart to view the cart contents.

Congratulations! You have successfully built a shopping cart application using Python and Flask. You can further enhance the application by adding features like removing items from the cart, calculating the total price, and implementing the checkout process.

Conclusion

In this tutorial, we have learned how to create a shopping cart application using Python and Flask. We covered the basics of Flask routing, creating templates, and rendering them in the application. Additionally, we implemented the shopping cart functionality by adding routes to view products, add them to the cart, and view the cart contents. By following this tutorial, you should now have a solid foundation for building more complex web applications using Flask. Happy coding!