26 – Real-World Python Projects – Simple E-commerce Backend

๐ŸŽฏ Project Objective

To design a Python program that handles products, users, carts, and orders โ€” the essential logic behind an e-commerce website (no front-end required).


๐Ÿงฉ 1. Overview

Youโ€™ll build a console-based backend that supports:

  • โœ… User registration/login
  • ๐Ÿ›๏ธ Product catalog management
  • ๐Ÿ›’ Cart and checkout system
  • ๐Ÿ’ณ Order tracking

Weโ€™ll simulate database operations using JSON files, but it can easily upgrade to SQLite or MySQL later.


โš™๏ธ 2. Setup

Weโ€™ll use:

LibraryPurpose
jsonStore and read database files
uuidGenerate unique IDs for products/orders
datetimeTimestamp orders

No external installation needed โ€” all built-in!


๐Ÿงฑ 3. File Structure

ecommerce_backend/
โ”‚
โ”œโ”€โ”€ main.py
โ”œโ”€โ”€ users.json
โ”œโ”€โ”€ products.json
โ””โ”€โ”€ orders.json

๐Ÿ“ฆ 4. Starter Code

main.py

import json, uuid, datetime, os

# ---------- DATABASE HANDLERS ----------
def load_data(filename):
    if not os.path.exists(filename):
        return []
    with open(filename, "r") as f:
        return json.load(f)

def save_data(filename, data):
    with open(filename, "w") as f:
        json.dump(data, f, indent=4)

# ---------- USER SYSTEM ----------
def register_user():
    users = load_data("users.json")
    name = input("Enter your name: ")
    email = input("Enter your email: ")
    password = input("Enter password: ")

    for u in users:
        if u["email"] == email:
            print("โŒ Email already registered.")
            return

    user = {
        "id": str(uuid.uuid4()),
        "name": name,
        "email": email,
        "password": password
    }
    users.append(user)
    save_data("users.json", users)
    print("โœ… Registration successful!")

def login_user():
    users = load_data("users.json")
    email = input("Email: ")
    password = input("Password: ")

    for u in users:
        if u["email"] == email and u["password"] == password:
            print(f"โœ… Welcome {u['name']}!")
            return u
    print("โŒ Invalid credentials.")
    return None

๐Ÿ›๏ธ 5. Product Management

def add_product():
    products = load_data("products.json")
    name = input("Product name: ")
    price = float(input("Price: "))
    stock = int(input("Stock quantity: "))

    product = {
        "id": str(uuid.uuid4()),
        "name": name,
        "price": price,
        "stock": stock
    }
    products.append(product)
    save_data("products.json", products)
    print("โœ… Product added successfully!")

def list_products():
    products = load_data("products.json")
    if not products:
        print("No products available.")
        return
    print("\n๐Ÿ›’ Product List:")
    for p in products:
        print(f"ID: {p['id'][:6]} | {p['name']} - โ‚น{p['price']} (Stock: {p['stock']})")

๐Ÿ›’ 6. Cart & Checkout

cart = []

def add_to_cart():
    products = load_data("products.json")
    list_products()
    pid = input("Enter product ID to add to cart: ")
    for p in products:
        if p["id"].startswith(pid):
            qty = int(input("Enter quantity: "))
            if qty <= p["stock"]:
                cart.append({"product": p, "qty": qty})
                print(f"โœ… Added {qty} x {p['name']} to cart")
                return
            else:
                print("โŒ Not enough stock.")
                return
    print("โŒ Product not found.")

def view_cart():
    if not cart:
        print("๐Ÿ›’ Cart is empty.")
        return
    print("\n๐Ÿงพ Your Cart:")
    total = 0
    for item in cart:
        subtotal = item["product"]["price"] * item["qty"]
        total += subtotal
        print(f"{item['product']['name']} ร— {item['qty']} = โ‚น{subtotal}")
    print(f"\nTotal: โ‚น{total}")

def checkout(user):
    if not cart:
        print("Cart empty.")
        return
    products = load_data("products.json")
    orders = load_data("orders.json")

    total = sum(item["product"]["price"] * item["qty"] for item in cart)
    order = {
        "id": str(uuid.uuid4()),
        "user_id": user["id"],
        "items": [{"name": i["product"]["name"], "qty": i["qty"]} for i in cart],
        "total": total,
        "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    }

    # Update stock
    for item in cart:
        for p in products:
            if p["id"] == item["product"]["id"]:
                p["stock"] -= item["qty"]

    save_data("products.json", products)
    orders.append(order)
    save_data("orders.json", orders)
    cart.clear()

    print(f"โœ… Order placed! Total amount: โ‚น{total}")

๐Ÿงญ 7. Main Menu

def main():
    print("=== ๐Ÿ›’ Simple E-commerce Backend ===")
    user = None

    while True:
        print("\n1. Register")
        print("2. Login")
        print("3. Add Product (Admin)")
        print("4. List Products")
        print("5. Add to Cart")
        print("6. View Cart")
        print("7. Checkout")
        print("8. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            register_user()
        elif choice == "2":
            user = login_user()
        elif choice == "3":
            add_product()
        elif choice == "4":
            list_products()
        elif choice == "5":
            if user: add_to_cart()
            else: print("๐Ÿ”’ Please log in first.")
        elif choice == "6":
            view_cart()
        elif choice == "7":
            if user: checkout(user)
            else: print("๐Ÿ”’ Please log in first.")
        elif choice == "8":
            print("๐Ÿ‘‹ Exiting...")
            break
        else:
            print("โŒ Invalid choice.")
if __name__ == "__main__":
    main()

๐Ÿง  8. How It Works

ComponentDescription
users.jsonStores users and credentials
products.jsonHolds product catalog
orders.jsonTracks completed orders
cartTemporary session cart in memory

๐Ÿ’ก 9. Enhancement Ideas

FeatureDescription
๐Ÿ’ณ Payment SimulationSimulate payments via wallet or mock API
๐Ÿ“ฆ Shipping StatusAdd delivery tracking & updates
๐Ÿ‘ค Admin PanelDifferentiate between customers & admins
๐Ÿงพ InvoiceGenerate PDF invoice using reportlab
๐Ÿ—„๏ธ DatabaseUse SQLite instead of JSON for real persistence
๐ŸŒ Flask APIExpose endpoints for a front-end app or mobile app

โœ… Summary

ModulePurpose
๐Ÿง User SystemRegister, Login
๐Ÿ›๏ธ Product ManagementAdd & list products
๐Ÿ›’ Cart SystemAdd, view, checkout
๐Ÿ’พ PersistenceJSON-based data storage
๐Ÿ’ก ExtendableCan upgrade to full web backend


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *