In this post, I will share how we can implement the concept of fast e-commerce-based applications such as Blinkit and Zepto in Python. We will deliver groceries in seconds. In this application, you will learn a lot of things. I have designed it independently and will keep improving it with more ideas. Let’s see how we can implement an e-commerce app in Python
What You Will Learn
In this app, users can:
- See the current inventory and product details
- They can purchase the items in groups as well
- They can manage their cart items
- Users can see their expenses based on their purchase history.
- Users can place orders and pay via cash (You can also implement online payment)
- Every time users buy something we will also handle the inventory.
Prerequisites
- Understanding of Functions in Python
- Understanding of Python OOP
- Understanding of time and datetime modules, and Pandas and Matplotlib libraries.
Before we start: Please note that this is just a user-facing implementation, not the whole app, which means e-commerce applications often involve many parties. This app works and shows you how you can develop your app. I have not implemented everything but you can add new features. This app should give you an idea and hope you can further improve it and share your ideas.
Let’s get started. Valuable feedback and suggestions are welcome.
Code
Make sure to open your Jupyter Notebook Or Code Editor to start coding it out. Understand every line and ask if any doubt in the forum.
# let's first create the shopping items
import pandas as pd
items = pd.DataFrame({
"Papaya Semi Ripe" : pd.Series(["Vegetables", "900g", 99, 10], index = ["Categories", "Details", "Price", "Stock"]),
"Ginger" : pd.Series(["Vegetables", "200g", 43, 10], index = ["Categories", "Details", "Price", "Stock"]),
"Chicken Breast" : pd.Series(["Meat", "500g", 220, 10], index = ["Categories", "Details", "Price", "Stock"]),
"Egg White" : pd.Series(["Meat", "6pc", 76, 10], index = ["Categories", "Details", "Price", "Stock"]),
})
Code language: Python (python)
import time
import datetime
class App:
def __init__(self):
""" This application is designed to showcase how one can design an ecommerce platform using python and also to showcase
how one can understand the functioning of modern businessness like Zepto and Blinkit. This program just shows
the user facing functionality.
Author: Amritesh Kumar
Date: 22nd October 2022
"""
self.cart = []
self.ongoing_orders = []
self.orders_history = []
self.tl = []
self.expense = []
self.date = []
def logout(self):
""" To allow users to remove the app instance"""
print("To logout from your account. type 'del app' in your terminal")
def buy_items(self):
""" To allow users to add items to their cart"""
print(items)
print("\n")
while True:
name = input("Input Product Name")
if name not in items.columns:
print("Invalid Name.Try again.")
else:
quantity = int(input("Please enter the quantity of the product"))
if items[name]["Stock"] == 0:
print("Item out of stock. Please stay updated and buy something else :)")
elif quantity <= 0:
print("Enter a positive value")
elif quantity > items[name]["Stock"]:
print(f"Please use any value less than or equal to our current stock:{items[name]['Stock']}")
quantity = int(input("Please enter the quantity of the product"))
else:
amount = quantity * items[name]["Price"]
cart_details = {"Name": name, "Quantity": quantity, "Total Price": amount}
self.cart.append(cart_details)
response = input("Do you want to add more items Y/N?")
if response not in ["Y", "N"]:
print("Choose either Y or N")
response = input("Do you want to add more items Y/N?")
elif response == "Y":
continue
elif response == "N":
break
print(f"Your current order details are:{self.cart}")
print("\n")
def clear_cart(self):
"""In case user wants to clear his cart"""
self.cart.clear()
print("All the items have been removed")
def place_order(self):
"""Once the user is happy with his cart items. He can place order and sequence of events will take place."""
if len(self.cart) == 0:
print("Your cart is empty. Please add items to your cart")
else:
start_time = time.time()
date = datetime.datetime.now()
for i in self.cart:
items[i["Name"]]["Stock"] = items[i["Name"]]["Stock"] - i["Quantity"]
for i in self.cart:
a = i["Total Price"]
self.tl.append(a)
subtotal = sum(self.tl)
self.ongoing_orders = self.cart[:]
self.cart.clear()
print("Thank you. Your order has been placed. Please pay via cash/cards on delivery")
print("You subtotal is:", subtotal)
print("Please note: Order once placed can't be cancelled.")
print("\n")
time.sleep(5)
print("Order packed")
time.sleep(5)
print("Driver has been assigned to your order")
time.sleep(10)
print("Your order has been dispatched")
time.sleep(10)
print("Your order has reached your location")
time.sleep(5)
print("Connecting you to the driver...")
time.sleep(5)
print("Order delivered and verified by driver.")
duration = round((time.time() - start_time), 2)
time.sleep(5)
print("Thank you for purchasing with us. Your order has been delivered")
print(f"Aye! it took only {duration} seconds.")
delta = datetime.datetime.now()
delivered_order = {"Order_details": self.ongoing_orders[:],
"Subtotal": subtotal,
"Date": date.date().strftime('%y-%m-%d'),
"Placed at": date.time().strftime('%a %H:%M:%S'),
"Delivered at": delta.time().strftime('%a %H:%M:%S'),
"Duration in seconds": duration}
self.orders_history.append(delivered_order)
self.ongoing_orders.clear()
def contact_support(self):
""" User can reach out to the customer care executive for help"""
print("If you have any query related to our service or your orders. Please email us at help@groceryinmins.com")
print(""" A few things that you might be looking for:
1. Order once placed can't be cancelled or returned. We only offer exchange.
2. To leave your feedback, please email us
3. for any other queries reach out to us via email""")
def show_expense(self):
"""User can track his expenses date wise. """
for i in self.orders_history:
self.expense.append(i["Subtotal"])
self.date.append(i["Date"])
df = pd.DataFrame({"Spent" : self.expense }, index = [self.date])
df.plot(kind = "bar",
title = "User Purchase History",
xlabel = "Purchase Date",
ylabel = "Amount Spent",
rot = "vertical");
Code language: Python (python)
That’s it this should give you an idea of how you can create an e-commerce app in Python. Please code it out on your own in your Jupyter Notebook and see how this works. You can also allow users to create accounts. If you are interested in learning how to create a user registration and login form with validation in Python then check this post.