๐ฏ 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:
| Library | Purpose |
|---|---|
json | Store and read database files |
uuid | Generate unique IDs for products/orders |
datetime | Timestamp 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
| Component | Description |
|---|---|
users.json | Stores users and credentials |
products.json | Holds product catalog |
orders.json | Tracks completed orders |
cart | Temporary session cart in memory |
๐ก 9. Enhancement Ideas
| Feature | Description |
|---|---|
| ๐ณ Payment Simulation | Simulate payments via wallet or mock API |
| ๐ฆ Shipping Status | Add delivery tracking & updates |
| ๐ค Admin Panel | Differentiate between customers & admins |
| ๐งพ Invoice | Generate PDF invoice using reportlab |
| ๐๏ธ Database | Use SQLite instead of JSON for real persistence |
| ๐ Flask API | Expose endpoints for a front-end app or mobile app |
โ Summary
| Module | Purpose |
|---|---|
| ๐ง User System | Register, Login |
| ๐๏ธ Product Management | Add & list products |
| ๐ Cart System | Add, view, checkout |
| ๐พ Persistence | JSON-based data storage |
| ๐ก Extendable | Can upgrade to full web backend |

Leave a Reply