0% found this document useful (0 votes)
9 views46 pages

Online Shopping System with Python & SQL

Uploaded by

havenlyman015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views46 pages

Online Shopping System with Python & SQL

Uploaded by

havenlyman015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

This project is a simple yet useful creation developed by a student to understand how
Python and SQL can work together to make real-life systems like an online shopping
application. The main aim of this project is to show how Python can handle user input and
logic while SQL helps store all the important data safely.​
It gave me a good learning experience about coding, databases, and how the two connect
to make a complete working system.

Python Introduction
Python is one of the most popular and beginner-friendly programming languages used today.
It was developed by Guido van Rossum and first released in 1991. It is known for its simple
syntax, readability, and flexibility, making it a great choice for students and professionals
alike. In this project, Python has been used as the main programming language to handle all
logic and operations.

Key Features of Python:

1.​ Easy to Learn: The syntax is simple and very close to the English language.​

2.​ Versatile: It can be used for web development, data analysis, artificial intelligence,
and automation.​

3.​ Extensive Libraries: Python provides thousands of built-in libraries and modules
that make coding easier.​

4.​ Platform Independent: It runs smoothly on Windows, macOS, and Linux.​

SQL Introduction
SQL stands for Structured Query Language, and it is used to store, manage, and retrieve
data from databases. In this project, SQL has been used to keep records of products, users,
and their orders. It works as the backbone of the system by handling all the data operations
in a structured and organized way.

Key Features of SQL:

1.​ Data Management: Helps store, update, and retrieve large amounts of data easily.​

2.​ High Security: Provides user access control to keep data safe.​

3.​ Reliability: Ensures data accuracy and consistency even after multiple operation​
Project Objectives
The main objective of this project is to create a simple Online Shopping System using
Python and SQL. The idea is to make a small version of an e-commerce platform where
users can view products, select what they want, and place orders — all through Python’s
program interface. The database part, made using SQL, safely stores all product details,
customer data, and order records.

While working on this project, the goal was not just to make a working program but also to
understand how programming and databases work together in real-world applications. It
helped me learn how user data is handled, how queries work in SQL, and how Python can
be connected to a database to make a complete system.

Main Objectives of the Project:

1.​ To design a simple and user-friendly online shopping system.​

2.​ To connect Python with SQL and perform database operations easily.​

3.​ To allow users to view, add, and order products using the Python interface.​

4.​ To help the admin manage the database (add, update, or delete products).​

5.​ To understand the concept of data connectivity, query execution, and database
management using Python.​


Tools and Technologies Used
This project has been developed using a set of simple yet powerful tools and technologies.
Each tool plays an important role in building and running the Online Shopping System
smoothly. Below is a detailed explanation of the technologies used:

1. Python (Programming Language)

Python is the main programming language used in this project. It handles all the logic of the
system such as displaying products, taking user input, and connecting to the database.
Python is known for its clear syntax and is widely used in web development, automation, and
data analysis.

Role in the Project:

●​ Controls the flow of the program.​

●​ Connects with the MySQL database using connector libraries.​

●​ Handles operations like adding products, showing data, and placing orders.​

2. MySQL (Database Management System)

MySQL is an open-source relational database used to store and manage all the data of the
project. It stores details such as product information, user data, and orders in well-organized
tables.

Role in the Project:

●​ Stores and retrieves data efficiently.​

●​ Keeps records of products, users, and orders.​

●​ Ensures data integrity and security.​

3. MySQL Connector (Library)

MySQL Connector is a Python library that helps to connect the Python program with the
MySQL database. It allows the execution of SQL queries directly from Python code.

Role in the Project:

●​ Establishes connection between Python and MySQL.​

●​ Helps run SQL commands (like INSERT, UPDATE, DELETE, SELECT).​


●​ Transfers data between the program and the database.​

4. IDE (Integrated Development Environment)

For coding and testing the program, IDEs like IDLE and Visual Studio Code (VS Code)
were used. These platforms provide an easy-to-use interface for writing, running, and
debugging Python code.

Role in the Project:

●​ Helps in writing and executing Python programs.​

●​ Makes debugging and editing simpler.​

●​ Improves code readability.​

5. Operating System

The project was developed on Windows 10, but it can also run on Linux or macOS since
Python and MySQL are cross-platform compatible.

Role in the Project:

●​ Provides the environment for coding and running the system.​

●​ Supports installation of required software and libraries.


Modules of the System
The Online Shopping System project is divided into several modules. Each module
performs a specific role and helps the overall system work in a smooth and organized way.
The main modules of this system are the User Module, Admin Module, and Database
Module.

This modular structure makes it easy to understand, test, and improve each part of the
project separately. It also ensures that the whole program remains simple, flexible, and easy
to maintain.

1. User Module

The User Module is designed for the customers who use the online shopping system. It
allows users to browse through the list of products, select the items they want to buy, and
place their orders.

In this module, the user interacts directly with the Python interface. The system ensures that
the user experience is easy, smooth, and secure. Users can also register themselves, log in
to their accounts, and check their order history.

Main Functions:

●​ Allows users to register and log in using their personal details.​

●​ Displays all available products with prices and descriptions.​

●​ Provides an option to add products to the cart.​

●​ Enables users to place an order and view the order summary.​

●​ Allows users to logout safely after shopping.​

The user module focuses mainly on making the interface friendly and ensuring that all basic
shopping activities can be done easily.

2. Admin Module

The Admin Module is meant for the shop owner or administrator who controls and manages
the overall system. The admin has more power than a normal user. They can add, update, or
delete products, and also check the list of all orders placed by customers.

This module ensures that the store’s data is always up-to-date and accurate. It helps the
admin maintain the website and manage inventory effectively.

Main Functions:
●​ Add new products to the system with details like name, price, and stock quantity.​

●​ Update or edit existing products when prices or availability change.​

●​ Delete unavailable or outdated products from the list.​

●​ View customer orders to track sales and delivery status.​

●​ Manage all data efficiently to keep the system organized.​

The admin module is one of the most important parts of the project because it keeps
everything under control and ensures smooth business operations.

3. Database Module

The Database Module is the backbone of the entire system. It stores and manages all the
data related to users, products, and orders. This module is developed using MySQL, which
is connected to Python through SQL queries.

Whenever a user or admin performs an action—like logging in, adding a product, or placing
an order—the data is stored or retrieved from the database. The database ensures that
information is accurate, secure, and can be accessed quickly when required.

Main Functions:

●​ Store user details such as usernames, passwords, and contact information.​

●​ Maintain product information including product ID, name, price, and quantity.​

●​ Keep records of orders placed by users.​

●​ Provide quick data retrieval for Python programs to display results instantly.​

●​ Protect data from loss or unauthorized access.​

The database module acts as a bridge between the user/admin actions and the stored
information. It makes sure that every part of the system works properly and that data is
always safe and organized.

This modular division makes the Online Shopping System more structured, efficient, and
easy to use. Each module works together to create a smooth online shopping experience for
both customers and administrators.
Database Design
The database of this project is designed using MySQL, which is a popular relational
database management system. It helps to store, manage, and retrieve data efficiently. A
well-designed database is an essential part of any system because it ensures that the
information is organized and can be accessed quickly and accurately.

In this project, the database mainly stores information about the users who use the system
and the products that are managed within the system. The design focuses on simplicity,
clarity, and easy management, which is suitable for a student-level project.

Tables in the Database

1. Users Table (users)

The users table contains all the information about the users of the system. This table is
important because it allows the system to identify each user uniquely and provide
user-specific functionality like login and cart management.

●​ Fields in the Users Table:​

1.​ id → A unique number assigned to each user. This is the primary key and
ensures that each user can be distinguished from others.​

2.​ name → The name of the user.​

3.​ email → Email of the user, which is also used for login purposes.​

4.​ password → Password of the user, used for authentication.​

●​ Purpose:​
The users table allows the system to store individual user data securely and
supports login and account-related operations.​

2. Products Table (products)

The products table stores all the information about the products in the system. Every
product has specific details like name, price, category, and an image.

●​ Fields in the Products Table:​

1.​ id → A unique number assigned to each product. This is the primary key and
is set to auto-increment so that new products get unique IDs automatically.​

2.​ name → Name of the product.​


3.​ image_url → URL of the product image for display purposes.​

4.​ price → Price of the product.​

5.​ category → Category of the product such as Electronics, Food, Fashion, or


Beauty.​

●​ Purpose:​
The products table organizes all product information in one place. It allows the
system to display products, filter them by category or price, and manage
product details efficiently.​

Relationship Between Tables

Although the database currently has only two main tables (users and products), the
system also handles a cart functionality, which links users and products.

●​ Each user can select or add multiple products to their cart.​

●​ Each product can be added by multiple users independently.​

This creates a one-to-many relationship from the perspective of the user to products. The
relationship allows the system to track which products are selected by which users and
helps in managing operations like adding, removing, or updating items in the cart.
SQL Connectivity and How SQL Works with Python
In this project, SQL connectivity is one of the most important parts because it helps in
connecting the database with the Python program. Without SQL connectivity, the data stored
in the database would remain separate from the Python application, and the system would
not be able to work properly. By establishing this connection, we make sure that the data can
move smoothly between the program and the database whenever required.

Python is mainly used for performing logical operations and user interaction, while SQL
(Structured Query Language) is used for storing, organizing, and managing the data.
When these two work together, it becomes easy to build a complete working system where
data can be saved, updated, deleted, or retrieved in just a few seconds.

The database is created using MySQL, which is a very popular and easy-to-use database
management system. It stores all the information related to users and products in the form of
tables. Each table has rows and columns, just like an Excel sheet, where each row
represents a record and each column represents a field or attribute. Python can easily
connect to this database using the SQL connectivity feature and perform operations on
these tables.

The main purpose of using SQL connectivity in this project is to allow communication
between Python and MySQL. It helps in sending commands from Python to SQL and
getting the required data back. For example, when we want to see all the products available,
Python sends a command to MySQL saying, “Show me all the products,” and MySQL replies
with a list of all the product names, prices, and details stored in the database.

Through this connection, the system can perform all CRUD operations —​
C for Create,​
R for Read,​
U for Update, and​
D for Delete.​
These are the four main functions of any database, and they help in keeping the system
active and responsive. Python acts as the middle layer that takes the user’s input and
passes it to SQL, then takes the response from SQL and shows it to the user in a readable
format.

Working of SQL with Python

When the project starts running, Python first tries to connect to the MySQL database using
certain credentials like hostname, username, password, and database name. Once the
connection is successful, Python gets full access to the tables stored in that database.

If a user wants to add a new product or record, Python sends an INSERT command to SQL.​
If a user wants to view all records, Python sends a SELECT command.​
If the user updates a product price or name, Python sends an UPDATE command.​
And if the user removes a product, Python sends a DELETE command.
This process happens automatically in the background without the user needing to
understand SQL. The Python program handles everything with the help of SQL connectivity.
It makes the project more interactive and gives it a real-life working experience, just like how
online stores or data-management systems work.

The communication between Python and SQL is a two-way process:

1.​ Python to SQL: Python sends the request or query.​

2.​ SQL to Python: SQL processes the query and sends the result back.​

This back-and-forth process is what keeps the system functional and efficient.

Benefits of Using SQL Connectivity

There are several advantages of using SQL connectivity in this project:

1.​ Data Storage and Management:​


All the data is stored safely in a structured form, which can be easily accessed and
managed using SQL commands.​

2.​ Easy Data Handling:​


With the help of Python, the user can add or view information without directly
touching the database. Everything happens automatically through the program.​

3.​ Speed and Efficiency:​


SQL processes queries very quickly, so results are generated almost instantly. This
makes the system smooth and fast.​

4.​ Accuracy and Reliability:​


Since SQL is designed for database management, it ensures that the stored data is
always accurate and free from duplication or loss.​

5.​ User-Friendly Experience:​


The connection allows normal users to interact with data using Python’s simple
interface, rather than learning complicated SQL commands.​

6.​ Real-World Application:​


SQL connectivity teaches students how real applications manage their data in the
background. This same concept is used in professional apps, e-commerce websites,
and business systems.
Python Code

#!/usr/bin/env python3

import os, secrets, html

from [Link] import HTTPServer, BaseHTTPRequestHandler

from [Link] import SimpleCookie

from [Link] import urlparse, parse_qs, quote as urlquote

from decimal import Decimal, InvalidOperation

import [Link]

# ---- DB config ----

DB_HOST = [Link]("DB_HOST", "[Link]")

DB_USER = [Link]("DB_USER", "root")

DB_PASS = [Link]("DB_PASSWORD", "zen1234")

DB_NAME = [Link]("DB_NAME", "ecomshop")

def db_conn():

return [Link](

host=DB_HOST, user=DB_USER, password=DB_PASS,


database=DB_NAME, autocommit=False

)
# ---- Helpers ----

def money(x):

try:

return format(x if isinstance(x, Decimal) else Decimal(str(x)),


".2f")

except Exception:

return str(x)

def to_dec(v):

try: return Decimal(str(v))

except (InvalidOperation, TypeError): return None

def color_for_id(pid):

h = (pid * 47) % 360; s, l = 60, 70

def hue_to_rgb(p,q,t):

if t < 0: t += 1

if t > 1: t -= 1

if t < 1/6: return p + (q - p) * 6 * t

if t < 1/2: return q


if t < 2/3: return p + (q - p) * (2/3 - t) * 6

return p

H, S, L = h/360, s/100, l/100

if S == 0: r = g = b = L

else:

q = L * (1 + S) if L < 0.5 else L + S - L * S

p=2*L-q

r = hue_to_rgb(p, q, H + 1/3); g = hue_to_rgb(p, q, H); b =


hue_to_rgb(p, q, H - 1/3)

return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"

def svg_card(name, price, pid, w=240, h=160):

bg = color_for_id(pid)

def darken(hexcol, f=0.75):

r = int(hexcol[1:3],16); g = int(hexcol[3:5],16); b =
int(hexcol[5:7],16)

r = int(r*f); g = int(g*f); b = int(b*f)

return f"#{r:02x}{g:02x}{b:02x}"

bg2 = darken(bg)

name = [Link](name); price = money(price)

return f'''<svg xmlns="[Link] width="{w}"


height="{h}" viewBox="0 0 {w} {h}">

<defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1">


<stop offset="0%" stop-color="{bg}"/><stop offset="100%"
stop-color="{bg2}"/></linearGradient></defs>

<rect width="{w}" height="{h}" rx="10" fill="url(#g)"/>

<text x="50%" y="{h/2 - 6:.0f}" text-anchor="middle"


font-family="system-ui, sans-serif" font-size="18"
fill="#000000a0">{name}</text>

<text x="50%" y="{h/2 + 18:.0f}" text-anchor="middle"


font-family="system-ui, sans-serif" font-size="16"
font-weight="bold" fill="#000">{'₹'}{price}</text>

</svg>'''

def db_list_categories(conn):

cur = [Link]()

[Link]("SELECT DISTINCT category FROM products


WHERE category IS NOT NULL AND category <> '' ORDER BY
category")

cats = [r[0] for r in [Link]()]

[Link]()

return cats

def db_list_products(conn, categories=None, min_price=None,


max_price=None):
sql = "SELECT id, name, image_url, price, category FROM
products WHERE 1=1"

params = []

cats = [c for c in (categories or []) if c not in (None, "")]

if cats:

placeholders = ",".join(["%s"] * len(cats))

sql += f" AND category IN ({placeholders})"

[Link](cats)

mn = None if min_price in (None, "") else to_dec(min_price)

mx = None if max_price in (None, "") else to_dec(max_price)

if mn is not None:

sql += " AND price >= %s"; [Link](mn)

if mx is not None:

sql += " AND price <= %s"; [Link](mx)

sql += " ORDER BY id ASC"

cur = [Link](dictionary=True)

[Link](sql, tuple(params))

rows = [Link]()

[Link]()

return rows

def db_get_product(conn, pid):


cur = [Link](dictionary=True)

[Link]("SELECT id, name, image_url, price, category FROM


products WHERE id=%s", (pid,))

row = [Link](); [Link](); return row

def db_find_user_by_email(conn, email):

cur = [Link](dictionary=True)

[Link]("SELECT id, name, email, password FROM users


WHERE email=%s", (email,))

row = [Link](); [Link](); return row

def db_create_user(conn, name, email, password):

cur = [Link]()

[Link]("SELECT COALESCE(MAX(id),0)+1 FROM users")

next_id = [Link]()[0]

[Link]("INSERT INTO users (id, name, email, password)


VALUES (%s, %s, %s, %s)",

(next_id, name, email, password))

[Link]()

[Link]()

return next_id
SESSIONS = {}

def nav_html(sess):

if [Link]("user"):

u = sess["user"]

return f'<div class="nav">Logged in:


<strong>{[Link](u["name"])}
({[Link](u["email"])})</strong> | <a
href="/logout">Logout</a></div>'

return '<div class="nav"> <a href="/signup">Sign up</a> <a


href="/login">Log in</a></div>'

def render_index(sess, products, categories, selected_cats,


min_price, max_price,

cart_items, cart_total, cart_count, msg=""):

cat_checks = [
f'<label><input type="checkbox" name="category"
value="{[Link](c)}" {"checked" if c in selected_cats else ""}>
{[Link](c)}</label>'

for c in categories

prod_cards = []

for p in products:

src = p["image_url"] or f"/img/{p['id']}?w=240&h=160"

if [Link]("user"):

add_block = f'''

<form method="get" action="/add" class="addform">

<input type="hidden" name="product_id"


value="{p['id']}">

<label>Qty <input type="number" name="qty" value="1"


min="1" class="qty"></label>

<button type="submit">Add to Cart</button>

</form>

'''

else:

add_block = f'''

<a class="btn-disabled"
href="/login?next={urlquote('/')}">add to cart</a>

'''

prod_cards.append(f'''

<div class="card">
<img class="thumb" src="{src}"
alt="{[Link](p['name'])}">

<div class="name">{[Link](p['name'])}</div>

<div class="cat">{[Link](p['category'] or '')}</div>

<div class="price">₹{money(p['price'])}</div>

{add_block}

</div>

''')

cart_rows = []

for it in cart_items:

cart_rows.append(f'''

<tr>

<td>{[Link](it["name"])}</td>

<td>₹{money(it["price"])}</td>

<td>{it["quantity"]}</td>

<td>₹{money(it["line_total"])}</td>

<td><a
href="/remove?product_id={it["product_id"]}">Remove</a></td>

</tr>

''')
msg_html = f'<div class="msg">{[Link](msg)}</div>' if
(msg and msg != "ordered") else ""

return f'''<!doctype html>

<html>

<head>

<meta charset="utf-8"><meta name="viewport"


content="width=device-width, initial-scale=1">

<title>Shop</title>

<style>

:root {{ --gap: 12px; : #ddd; }}

* {{ box-sizing: border-box; }}

body {{ font-family: system-ui, -apple-system, Segoe UI, Roboto,


sans-serif; margin: 0; padding: 16px; background:#fafafa; }}

h1 {{ margin: 0 0 12px; }}

.nav {{ margin: 6px 0 12px; }}

.layout {{ display:grid; grid-template-columns: 260px 1fr; gap:


var(--gap); align-items:start; }}

@media (max-width: 900px) {{ .layout {{ grid-template-columns:


1fr; }} }}

[Link] {{ background:#fff; border:1px solid var( );


border-radius:8px; padding:12px; position:sticky; top:12px; }}

.filters h3 {{ margin: 0 0 8px; }}

.filters .group {{ margin-bottom:10px; display:flex;


flex-direction:column; gap:6px; max-height: 50vh; overflow:auto; }}
.filters .row {{ display:flex; gap:8px; align-items:center; }}

.grid {{ display:grid; grid-template-columns: repeat(auto-fill,


minmax(220px, 1fr)); gap: var(--gap); }}

.card {{ background:#fff; border:1px solid var( );


border-radius:10px; padding:8px; display:flex;
flex-direction:column; gap:6px; }}

.thumb {{ width:100%; height:auto; border-radius:8px;


border:1px solid #ccc; }}

.name {{ font-size:16px; font-weight:600; }}

.cat {{ font-size:12px; color:#666; }}

.price {{ font-weight:700; }}

.addform {{ display:flex; gap:8px; align-items:center; }}

.addform .qty {{ width:70px; padding:4px; }}

.btn-disabled {{ display:inline-block; padding:6px 10px;


border:1px solid #aaa; color:#666; text-decoration:none;
border-radius:6px; pointer-events:auto; }}

.msg {{ background:#e7ffe7; border:1px solid #b5e6b5;


padding:8px 10px; border-radius:6px; margin:8px 0; }}

/* Floating cart button */

#cartBtn {{ position: absolute; top: 10px; right: 10px;

cursor:pointer; z-index: 999;}}

/* Cart overlay modal */


#overlay {{ position:fixed; inset:0; background:rgba(0,0,0,0.45);
display:none; align-items:center; justify-content:center; z-index:
1000; }}

#[Link] {{ display:flex; }}

#modal {{ width:min(700px, 92vw); max-height:80vh;


overflow:auto; background:#fff; border-radius:10px; border:1px
solid var( ); }}

#modal header {{ display:flex; align-items:center;


justify-content:space-between; padding:10px 12px;
border-bottom:1px solid var( ); }}

#modal .body {{ padding:10px 12px; }}

#modal table {{ width:100%; border-collapse: collapse; }}

#modal th, #modal td {{ border:1px solid var( ); padding:6px;


text-align:left; }}

#closeCart {{ background:none; border:none; font-size:18px;


cursor:pointer; }}

.checkout {{ margin-top:8px; display:inline-block; padding:8px


12px; border:1px solid #444; border-radius:6px;
text-decoration:none; }}

</style>

</head>

<body>

<h1>Shop</h1>

{nav_html(sess)}

{msg_html}
<div class="layout">

<aside class="filters">

<h3>Filters</h3>

<form method="get" action="/">

<div class="group">

<strong>Categories</strong>

{''.join(cat_checks) if cat_checks else '<em>No


categories</em>'}

</div>

<div class="group">

<strong>Price</strong>

<div class="row">Min <input type="number" step="0.01"


name="min_price" value="{[Link](str(min_price or
''))}"></div>

<div class="row">Max <input type="number" step="0.01"


name="max_price" value="{[Link](str(max_price or
''))}"></div>

</div>

<div class="row">

<button type="submit">Apply</button>

<a href="/" style="margin-left:8px;">Clear</a>

</div>

</form>

</aside>
<main>

<div class="grid">

{''.join(prod_cards) if prod_cards else '<em>No products


found</em>'}

</div>

</main>

</div>

<button id="cartBtn">Cart ({cart_count})</button>

<div id="overlay">

<div id="modal" onclick="[Link]()">

<header>

<strong>Your Cart</strong>

<button id="closeCart" title="Close">✕</button>

</header>

<div class="body">

<table>

<tr><th>Product</th><th>Price</th><th>Qty</th><th>Line</th><th>
</th></tr>
{''.join(cart_rows) if cart_rows else '<tr><td
colspan="5"><em>Cart is empty</em></td></tr>'}

<tr><td colspan="3"
style="text-align:right"><strong>Total</strong></td><td
colspan="2"><strong>₹{money(cart_total)}</strong></td></tr>

</table>

<p><a class="checkout" href="/checkout">Checkout</a></p>

<p style="color:#666; font-size:12px;">Note: Add to


cart/checkout requires login.</p>

</div>

</div>

</div>

<script>

(function(){{

var btn = [Link]('cartBtn');

var overlay = [Link]('overlay');

var closeBtn = [Link]('closeCart');

if (btn) [Link]('click', function() {{


[Link]('show'); }});

if (closeBtn) [Link]('click', function() {{


[Link]('show'); }});

[Link]('click', function() {{
[Link]('show'); }});
// show success alert after checkout

var p = new URLSearchParams([Link]);

if ([Link]('msg') === 'ordered') {{

alert('Order placed successfully');

[Link]('msg');

var newUrl = [Link] + ([Link]() ? '?' +


[Link]() : '');

[Link](null, '', newUrl);

}}

}})();

</script>

</body>

</html>'''

def render_auth(title, action, error="", next_url=""):

err = f'<p style="color:red">{[Link](error)}</p>' if error else


""

hidden_next = f'<input type="hidden" name="next"


value="{[Link](next_url)}">' if next_url else ""

name_field = '<div>Name: <input type="text" name="name"


required></div>' if 'signup' in action else ''

return f'''<!doctype html>


<html><head><meta
charset="utf-8"><title>{[Link](title)}</title></head>

<body>

<h1>{[Link](title)}</h1>

{err}

<form method="post" action="{action}">

{name_field}

<div>Email: <input type="email" name="email" required></div>

<div>Password: <input type="password" name="password"


required></div>

{hidden_next}

<div><button type="submit">{[Link](title)}</button></div>

</form>

<p><a href="/">Back</a></p>

</body></html>'''

# ---- HTTP handler ----

class Handler(BaseHTTPRequestHandler):

new_cookie = None

def get_session(self):

cookie = SimpleCookie([Link]("Cookie", ""))


sid = cookie["sid"].value if "sid" in cookie else None

if not sid or sid not in SESSIONS:

sid = secrets.token_hex(16)

SESSIONS[sid] = {"user": None, "cart": {}}

self.new_cookie = f"sid={sid}; Path=/; HttpOnly;


SameSite=Lax"

return sid, SESSIONS[sid]

def set_cookie_if_new(self):

if self.new_cookie:

self.send_header("Set-Cookie", self.new_cookie)

self.new_cookie = None

def send_html(self, html_text, status=200):

body = html_text.encode("utf-8")

self.send_response(status)

self.send_header("Content-Type", "text/html; charset=utf-8")

self.send_header("Cache-Control", "no-store")

self.send_header("Content-Length", str(len(body)))

self.set_cookie_if_new()

self.end_headers()
[Link](body)

def send_svg(self, svg_text, status=200):

body = svg_text.encode("utf-8")

self.send_response(status)

self.send_header("Content-Type", "image/svg+xml;
charset=utf-8")

self.send_header("Cache-Control", "public, max-age=3600")

self.send_header("Content-Length", str(len(body)))

self.set_cookie_if_new()

self.end_headers()

[Link](body)

def redirect(self, location):

self.send_response(303)

self.send_header("Location", location)

self.set_cookie_if_new()

self.end_headers()

def parse_post(self):
length = int([Link]("Content-Length", "0") or "0")

body = [Link](length).decode("utf-8", errors="ignore")

return {k: (v[0] if isinstance(v, list) else v) for k, v in


parse_qs(body).items()}

def do_GET(self):

parsed = urlparse([Link])

path = [Link]

qs = parse_qs([Link])

sid, sess = self.get_session()

qlist = lambda k: [Link](k, [])

qstr = lambda k, d="": ([Link](k, [d])[0] or "")

try:

conn = db_conn()

except Exception as e:

self.send_html(f"<h1>DB
Error</h1><p>{[Link](str(e))}</p>", 500)

return

try:
if path == "/":

categories = db_list_categories(conn)

selected_cats = qlist("category")

products = db_list_products(

conn, categories=selected_cats,

min_price=qstr("min_price"),
max_price=qstr("max_price")

# Build cart snapshot from session cart

items = []

total = Decimal("0.00")

count = 0

for pid, qty in sorted(sess["cart"].items()):

prod = db_get_product(conn, pid)

if not prod: continue

line = prod["price"] * qty

total += line; count += qty

[Link]({"product_id": pid, "name":


prod["name"], "price": prod["price"], "quantity": qty, "line_total":
line})

page = render_index(

sess, products, categories, selected_cats,

min_price=qstr("min_price"),
max_price=qstr("max_price"),
cart_items=items, cart_total=total, cart_count=count,
msg=qstr("msg")

self.send_html(page); [Link](); return

if path == "/signup":

next_url = qstr("next", "/")

self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", next_url=next_url))

[Link](); return

if path == "/login":

next_url = qstr("next", "/")

self.send_html(render_auth("Log in",
f"/login?next={[Link](next_url)}", next_url=next_url))

[Link](); return

if path == "/logout":

sess["user"] = None

[Link]("/?msg=Logged+out"); [Link](); return


if path == "/add":

# Require login

if not [Link]("user"):

[Link]("/login?next=" + urlquote([Link]));
[Link](); return

try:

pid = int(qstr("product_id", "0"))

qty = int(qstr("qty", "1"))

except ValueError:

[Link]("/?msg=Invalid+input"); [Link]();
return

if pid <= 0 or qty <= 0:

[Link]("/?msg=Invalid+input"); [Link]();
return

prod = db_get_product(conn, pid)

if not prod:

[Link]("/?msg=Product+not+found");
[Link](); return

sess["cart"][pid] = sess["cart"].get(pid, 0) + qty

[Link]("/?msg=Added+to+cart"); [Link]();
return

if path == "/remove":
if not [Link]("user"):

[Link]("/login?next=" + urlquote([Link]));
[Link](); return

try:

pid = int(qstr("product_id", "0"))

except ValueError:

[Link]("/?msg=Invalid+input"); [Link]();
return

if pid in sess["cart"]:

del sess["cart"][pid]

[Link]("/?msg=Removed")

else:

[Link]("/?msg=Item+not+in+cart")

[Link](); return

if path == "/checkout":

if not [Link]("user"):

[Link]("/login?next=/checkout"); [Link]();
return

if not sess["cart"]:

[Link]("/?msg=Cart+is+empty"); [Link]();
return

# Only alert and clear (no DB)


sess["cart"].clear()

[Link]("/?msg=ordered"); [Link](); return

if [Link]("/img/"):

id_str = path[len("/img/"):].split(".", 1)[0]

try:

pid = int(id_str)

except ValueError:

self.send_html("Not found", 404); [Link](); return

prod = db_get_product(conn, pid)

if not prod:

self.send_html("Not found", 404); [Link](); return

w = qstr("w", "240"); h = qstr("h", "160")

try: w = int(w); h = int(h)

except ValueError: w, h = 240, 160

self.send_svg(svg_card(prod["name"], prod["price"],
prod["id"], w=w, h=h)); [Link](); return

self.send_html("Not found", 404); [Link](); return


except Exception as e:

try: [Link]()

except: pass

self.send_html(f"<h1>Error</h1><pre>{[Link](str(e))}</pre>",
500)

def do_POST(self):

parsed = urlparse([Link])

path = [Link]

qs = parse_qs([Link])

qstr = lambda k, d="": ([Link](k, [d])[0] or "")

sid, sess = self.get_session()

try:

conn = db_conn()

except Exception as e:

self.send_html(f"<h1>DB
Error</h1><p>{[Link](str(e))}</p>", 500)

return
try:

if path == "/signup":

form = self.parse_post()

name = ([Link]("name","") or "").strip()

email = ([Link]("email","") or "").strip().lower()

password = [Link]("password","") or ""

next_url = [Link]("next","") or qstr("next","/")

if not name or not email or not password:

self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", "All fields required",
next_url)); [Link](); return

if db_find_user_by_email(conn, email):

self.send_html(render_auth("Sign up",
f"/signup?next={[Link](next_url)}", "Email already in use",
next_url)); [Link](); return

uid = db_create_user(conn, name, email, password)

sess["user"] = {"id": uid, "name": name, "email": email}

[Link](next_url or "/"); [Link](); return

if path == "/login":

form = self.parse_post()

email = ([Link]("email","") or "").strip().lower()

password = [Link]("password","") or ""


next_url = [Link]("next","") or qstr("next","/")

row = db_find_user_by_email(conn, email)

if not row or row["password"] != password:

self.send_html(render_auth("Log in",
f"/login?next={[Link](next_url)}", "Invalid email or
password", next_url)); [Link](); return

sess["user"] = {"id": row["id"], "name": row["name"],


"email": row["email"]}

[Link](next_url or "/"); [Link](); return

self.send_html("Not found", 404); [Link](); return

except Exception as e:

try: [Link]()

except: pass

self.send_html(f"<h1>Error</h1><pre>{[Link](str(e))}</pre>",
500)

def run(host="[Link]", port=8000):

httpd = HTTPServer((host, port), Handler)

print(f"Serving on [Link]
httpd.serve_forever()

if __name__ == "__main__":

run()
SQL Code
CREATE DATABASE ecomshop;

CREATE TABLE users (

id INT PRIMARY KEY,

name VARCHAR(50),

email VARCHAR(100),

password VARCHAR(100)

);

CREATE TABLE products (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

image_url VARCHAR(255),

price DECIMAL(10,2),

category VARCHAR(50)

);

INSERT INTO products (name, image_url, price, category) VALUES

('Herbal Shampoo',
'[Link] 125.99, 'Beauty
and Personal Care'),

('Face Moisturizer',
'[Link] 128.49, 'Beauty
and Personal Care'),

('Perfume Spray',
'[Link]
pg', 315.00, 'Beauty and Personal Care'),
('Wireless Earbuds',
'[Link]
=1727669669', 149.99, 'Electronics'),

('Smartwatch',
'[Link]
pg', 279.99, 'Electronics'),

('Bluetooth Speaker',
'[Link]
-9138-0bd90874391e_1300x.png?v=1709717442', 129.99, 'Electronics'),

('Men T-Shirt',
'[Link]
th=800', 312.99, 'Fashion and Apparel'),

('Women Dress', '[Link]


224.99, 'Fashion and Apparel'),

('Sneakers', '[Link] 445.00,


'Fashion and Apparel'),

('Pasta Pack',
'[Link]
, 12.99, 'Food'),

('Organic Honey',
'[Link]
g', 216.49, 'Food'),

('Green Tea Box',


'[Link]
g', 44.25, 'Beverages'),

('Energy Drink',
'[Link]
', 211.99, 'Beverages'),

('Wooden Chair',
'[Link]
, 139.00, 'Beverages');
How the Code Works Behind the System
The project is a mini e-commerce web application developed using Python and
MySQL. It demonstrates the integration of a programming language with a
database to manage users, products, and transactions in a web-based
environment. This explanation covers the interaction between Python and
SQL, user session management, product display, cart functionality, and
checkout operations.

1. Python and SQL Connectivity


The system connects Python to MySQL using the [Link] library.
This connection allows Python to perform operations on the database,
including reading product details, managing users, and updating records. The
function db_conn() establishes this connection using host, username,
password, and database name.

The database contains two main tables:

●​ users – stores user information (id, name, email, password).​

●​ products – stores product details (id, name, image_url, price,


category).​

SQL handles permanent storage and retrieval of data, while Python handles
application logic, computation, and dynamic display to users.

2. Handling User Requests


The system uses Python’s HTTP server ([Link]) to handle user
requests. The Handler class is responsible for all GET and POST requests.

For example, when a user visits the homepage (/):

1.​ Python connects to the database.​

2.​ It fetches categories using db_list_categories().​

3.​ It retrieves products using db_list_products().​


4.​ It reads the user’s cart from the session and calculates totals.​

5.​ It dynamically generates HTML with the product and cart information.​

This ensures that users always see up-to-date data on the website.

3. User Authentication and Session Management


The project includes signup, login, and logout functionality:

●​ Signup: Checks if the email exists using db_find_user_by_email(). If


not, a new user is added with db_create_user().​

●​ Login: Verifies the email and password against the database.​

●​ Logout: Clears the session.​

Sessions are stored using cookies (SimpleCookie) and a Python dictionary


(SESSIONS). Each session maintains the user’s login status and cart items.
Cookies ensure session persistence across multiple requests.

4. Product Listing and Cart System


Products are fetched from the database and displayed dynamically:

●​ Products with image URLs are displayed as images.​

●​ Products without images are displayed using dynamically generated


SVG cards via the svg_card() function.​

●​ Users can add items to their cart. The session dictionary


(sess["cart"]) tracks items and quantities.​

●​ The cart modal shows product details, quantity, price, line total, and
total cart amount.​

Python updates the cart and reflects changes instantly in the user interface.
5. Checkout Process
The checkout process simulates order placement:

1.​ Confirms the user is logged in.​

2.​ Ensures the cart is not empty.​

3.​ Clears the cart and displays a success message.​

Although no actual order is stored in the database, this flow simulates a real
e-commerce checkout experience.

6. Python and SQL Interaction


Python interacts with the database by sending SQL queries:

Fetching products or categories:​



SELECT DISTINCT category FROM products;
SELECT id, name, price, category FROM products WHERE category IN
(...) AND price BETWEEN ...;

1.​

Creating a new user:​



INSERT INTO users (id, name, email, password) VALUES (...);

2.​

Finding a user for login:​



SELECT id, name, email, password FROM users WHERE email=%s;

3.​

Fetching a single product:​



SELECT id, name, price, category FROM products WHERE id=%s;

4.​

Cursors in Python ([Link]()) execute these queries and fetch results. Transactions
are committed using [Link]() for permanent changes.
7. Error Handling and Data Security
The system includes multiple safeguards:

●​ Database connection errors are caught and displayed gracefully.​

●​ User input is sanitized using [Link]() to prevent malicious


entries.​

●​ Prices and quantities are validated using Python’s Decimal module for
precision.​

●​ Only logged-in users can add items to the cart or checkout.​

These measures ensure consistent data an a secure system.

You might also like