Creating an E-Commerce Shopping Cart with Python

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. Creating the Shopping Cart
  5. Adding Products
  6. Displaying the Cart
  7. Updating the Cart
  8. Conclusion

Overview

In this tutorial, we will create a simple e-commerce shopping cart using Python. By the end of this tutorial, you will have a basic understanding of how to implement a shopping cart functionality in a web application.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. It is also recommended to have knowledge of HTML and CSS for the front-end implementation.

Setup

To begin, make sure you have Python installed on your computer. You can download the latest version of Python from the official Python website.

Additionally, we will use the Flask framework to develop the web application. You can install Flask using the following command: python pip install flask

Creating the Shopping Cart

First, let’s create a new directory for our project. Open a terminal or command prompt and run the following command: bash mkdir shopping-cart cd shopping-cart Next, create a Python virtual environment to isolate the project dependencies. Run the following command: bash python -m venv env Activate the virtual environment:

  • On Windows:
      env\Scripts\activate
    
  • On macOS and Linux:
      source env/bin/activate
    

    Now, let’s create a new Python file called app.py and open it in your favorite text editor:

      from flask import Flask
    	
      app = Flask(__name__)
    	
      @app.route('/')
      def home():
          return 'Welcome to the Shopping Cart!'
    	
      if __name__ == '__main__':
          app.run(debug=True)
    

    Save the file. This is a basic Flask application that will display a welcome message when accessed through the root URL.

To run the application, execute the following command in the terminal: bash flask run You should see an output similar to this: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Open your web browser and enter http://localhost:5000 in the address bar. You should see the welcome message displayed on the webpage.

Adding Products

Now that we have our basic application set up, let’s add some products that the user can select and add to their shopping cart.

Create a new directory called templates within the shopping-cart directory. This directory will contain our HTML templates.

Inside the templates directory, create a new file called products.html and open it in your text editor: ```html

<!DOCTYPE html>
<html>
<head>
    <title>Products</title>
</head>
<body>
    <h1>Available Products</h1>
    <ul>
        <li><a href="{{ url_for('add_to_cart', product='product1') }}">Product 1</a></li>
        <li><a href="{{ url_for('add_to_cart', product='product2') }}">Product 2</a></li>
        <li><a href="{{ url_for('add_to_cart', product='product3') }}">Product 3</a></li>
    </ul>
</body>
</html>

``` This HTML template displays a list of available products as links. When the user clicks on a product, it will be added to their shopping cart.

Open the app.py file and add the following routes and function: ```python @app.route(‘/products’) def show_products(): return render_template(‘products.html’)

@app.route('/add_to_cart/<product>')
def add_to_cart(product):
    # Add the selected product to the shopping cart
    return f'{product} added to cart!'
``` Save the file and restart the Flask application by stopping the current process and running `flask run` again in the terminal.

Now, if you visit http://localhost:5000/products, you should see a list of products. Clicking on a product should display a message confirming that the product has been added to the cart.

Displaying the Cart

Let’s now implement the functionality to display the user’s shopping cart. Create a new file called cart.html inside the templates directory: ```html

<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart</title>
</head>
<body>
    <h1>Your Shopping Cart</h1>
    <ul>
        {% for product in cart %}
            <li>{{ product }}</li>
        {% endfor %}
    </ul>
</body>
</html>

``` This HTML template will display the products in the user's shopping cart.

In the app.py file, add the following route and function: python @app.route('/cart') def show_cart(): cart = ['product1', 'product2'] # Dummy data, replace with actual cart contents return render_template('cart.html', cart=cart) Save the file and restart the Flask application.

Now, if you visit http://localhost:5000/cart, you should see the products displayed in your shopping cart.

Updating the Cart

To allow the user to remove products from the cart or update quantities, we will use query parameters in the URL. Modify the products.html file as follows: ```html

<!DOCTYPE html>
<html>
<head>
    <title>Products</title>
</head>
<body>
    <h1>Available Products</h1>
    <ul>
        <li><a href="{{ url_for('add_to_cart', product='product1') }}">Product 1</a></li>
        <li><a href="{{ url_for('add_to_cart', product='product2') }}">Product 2</a></li>
        <li><a href="{{ url_for('add_to_cart', product='product3') }}">Product 3</a></li>
    </ul>

    <h1>Your Shopping Cart</h1>
    <ul>
        {% for product in cart %}
            <li>{{ product }} <a href="{{ url_for('remove_from_cart', product=product) }}">(Remove)</a></li>
        {% endfor %}
    </ul>
</body>
</html>

``` Add the following route and function to `app.py`:
```python
@app.route('/remove_from_cart/<product>')
def remove_from_cart(product):
    # Remove the selected product from the shopping cart
    return f'{product} removed from cart!'
``` Restart the Flask application.

Now, when you click on the “Remove” link next to a product in the cart, it should display a message confirming that the product has been removed from the cart.

Conclusion

In this tutorial, we have created a simple e-commerce shopping cart using Python and Flask. We implemented the functionality to add products to the cart, display the cart contents, and remove products from the cart.

You can further enhance this shopping cart by adding features like user authentication, persistent storage, and checkout/payment processing.