Transforming this basic client-server example into a full-fledged eCommerce application involves several steps, including defining a more comprehensive communication protocol, expanding the GUI to support multiple features, and incorporating database operations for storing product and user data. For the sake of simplicity, I'll present a simplified version of an eCommerce application where:
- The server manages product data and handles client requests.
- The client allows users to view products and send purchase requests.
This version will not cover all features typical of an eCommerce application, as that would be too extensive, but it will provide a foundational framework for the app.
Step 1: Define the Server (server.py)
The server will manage a list of products and handle requests from clients to view and purchase products.
import asyncio
import json
products = [
{'id': 1, 'name': 'Laptop', 'price': 1000, 'quantity': 5},
{'id': 2, 'name': 'Phone', 'price': 800, 'quantity': 10},
]
async def handle_client(reader, writer):
addr = writer.get_extra_info('peername')
print(f"Connection from {addr}")
async def send_product_list():
response = json.dumps({'type': 'product_list', 'products': products})
print(f"Send: {response}")
writer.write(response.encode())
await writer.drain()
async def process_request():
while True:
data = await reader.read(1024)
if not data:
break
message = json.loads(data.decode())
print(f"Received from {addr}: {message}")
if message['type'] == 'view_products':
await send_product_list()
elif message['type'] == 'purchase':
product_id = message['product_id']
quantity = message['quantity']
response = handle_purchase(product_id, quantity)
writer.write(json.dumps(response).encode())
await writer.drain()
await process_request()
writer.close()
await writer.wait_closed()
def handle_purchase(product_id, quantity):
for product in products:
if product['id'] == product_id:
if product['quantity'] >= quantity:
product['quantity'] -= quantity
return {'type': 'purchase', 'status': 'success', 'product': product}
else:
return {'type': 'purchase', 'status': 'failed', 'reason': 'insufficient stock'}
return {'type': 'purchase', 'status': 'failed', 'reason': 'product not found'}
async def main():
server = await asyncio.start_server(handle_client, '127.0.0.1', 8888)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())
Step 2: Define the Client (client.py)
The client will have a GUI that allows users to view the products and send purchase requests.
import asyncio
import threading
import tkinter as tk
from tkinter import messagebox
import json
class AsyncClient:
def __init__(self, host, port, on_message):
self.host = host
self.port = port
self.on_message = on_message
async def connect(self):
reader, writer = await asyncio.open_connection(self.host, self.port)
self.reader = reader
self.writer = writer
await self.listen()
async def listen(self):
while True:
data = await self.reader.read(1024)
if not data:
break
message = json.loads(data.decode())
self.on_message(message)
def send(self, message):
self.writer.write(json.dumps(message).encode())
class App:
def __init__(self, root):
self.root = root
self.root.title("E-commerce Client")
self.product_list = tk.Listbox(root)
self.product_list.pack()
self.entry = tk.Entry(root)
self.entry.pack()
self.purchase_button = tk.Button(root, text="Purchase", command=self.purchase_product)
self.purchase_button.pack()
self.client = AsyncClient('127.0.0.1', 8888, self.on_message)
self.loop = asyncio.get_event_loop()
threading.Thread(target=self.start_client, daemon=True).start()
self.request_product_list()
def start_client(self):
self.loop.run_until_complete(self.client.connect())
def request_product_list(self):
self.client.send({'type': 'view_products'})
def purchase_product(self):
selected = self.product_list.curselection()
if not selected:
messagebox.showwarning("Warning", "No product selected")
return
quantity = self.entry.get()
if not quantity.isdigit() or int(quantity) < 1:
messagebox.showwarning("Warning", "Invalid quantity")
return
product_id = self.product_list.get(selected).split(' ')[0]
message = {'type': 'purchase', 'product_id': int(product_id), 'quantity': int(quantity)}
self.client.send(message)
def on_message(self, message):
if message['type'] == 'product_list':
def update_list():
self.product_list.delete(0, tk.END)
for product in message['products']:
self.product_list.insert(tk.END, f"{product['id']} {product['name']} - ${product['price']} ({product['quantity']} available)")
self.root.after(0, update_list)
elif message['type'] == 'purchase':
def show_result():
if message['status'] == 'success':
messagebox.showinfo("Success", f"Purchased {message['product']['name']}")
else:
messagebox.showerror("Error", message['reason'])
self.request_product_list()
self.root.after(0, show_result)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()
Explanation
-
Server:
- Handles requests for viewing products and purchasing products.
- Maintains a list of products.
- Processes purchase requests, updating the product quantities as needed.
- Sends appropriate responses to the client.
-
Client:
- Displays products in a Tkinter
Listbox.
- Allows users to select a product and enter a quantity to purchase.
- Sends requests to the server and handles responses.
- Updates the display based on the server's response.
Instructions
- Save the server code in
server.py and run it (python server.py).
- Save the client code in
client.py and run it (python client.py).
- Use the client GUI to view products and send purchase requests.
This is a basic setup and should be expanded with proper error handling, authentication, and other features typical for an eCommerce application in a real-world scenario.