Scaling-up a pizza ordering service#
You are working in a pizza shop to earn some money as a student making pizzas. One day the shop owner says:
The last weeks the order have been decreasing. Maybe we have to reduce your hours. A customer complained that our website is too slow.
You don’t want to reduce your hours.
Maybe I may not be able to pay for my flat in København ☹️
you think desperately.
You have a software engineering background, so you offer your boss to analyze the code for the web server.
Do you see any problems with the following code?
How would you improve it?
Tip
Use netcat
to test it, e.g.,
$ netcat localhost 12345
as
Wrong number of pizzas, please try again
1
Thank you for ordering 1 pizzas!
from socket import create_server, socket
BUFFER_SIZE = 1024
ADDRESS = ("127.0.0.1", 12345)
class Server:
def __init__(self) -> None:
try:
print(f"Starting up at: {ADDRESS}")
self.server_socket: socket = create_server(ADDRESS)
except OSError:
self.server_socket.close()
print("\nServer stopped.")
def accept(self) -> socket:
conn, client_address = self.server_socket.accept()
print(f"Connected to {client_address}")
return conn
def serve(self, conn: socket) -> None:
"""Serve the incoming connection by sending and receiving data."""
try:
while True:
data = conn.recv(BUFFER_SIZE)
if not data:
break
try:
order = int(data.decode())
response = f"Thank you for ordering {order} pizzas!\n"
except ValueError:
response = "Wrong number of pizzas, please try again\n"
print(f"Sending message to {conn.getpeername()}")
# send a response
conn.send(response.encode())
finally:
print(f"Connection with {conn.getpeername()} has been closed")
conn.close()
def start(self) -> None:
"""Start the server by continuously accepting and serving incoming
connections."""
print("Server listening for incoming connections")
try:
while True:
conn = self.accept()
self.serve(conn)
finally:
self.server_socket.close()
print("\nServer stopped.")
if __name__ == "__main__":
server = Server()
server.start()
Credits#
Based on:
Grokking Concurrency by Kirill Bobrov
https://github.com/luminousmen/grokking_concurrency/blob/master/Chapter 10