Hello,
I’m stuck on implementing the set and get commands. Set passes no problem, but get does not.
Somehow, my code doesn’t recognize that GET is in the list of valid commands, but it recognizes SET.
Here’s my command processor, and main.py:
class CommandProcessor:
def __init__(self, data_oracle) -> None:
self.commands = {}
# partial of async def requries python >=3.8
self.commands["SET"] = partial(processSet, data_oracle)
self.commands["GET"] = partial(processGet, data_oracle)
self.commands["PING"] = processPing
self.commands["ECHO"] = partial(processEcho, data_oracle)
self.data_oracle = data_oracle
async def process(self, input):
# input is the output buffer of the parser
# should be either a simple string
# PING or an array command
if input == "PING":
# return "+PONG\r\n"
return "PONG"
assert len(input) > 0
if input[2].upper() not in self.commands:
print("Error command not found!")
return None
commandfunc = self.commands[input[2].upper()]
# unpack arguments are the function arguments
# order matters here
output = await commandfunc(*input[4::2])
return output
import asyncio
from .commands.command_processor import CommandProcessor
from .data_oracle import DataOracle
async def handle_connection(reader, writer):
addr = writer.get_extra_info("peername")
print(f"Connection from {addr}")
while True:
line = await reader.read(4096)
data_oracle = DataOracle()
command_processor = CommandProcessor(data_oracle)
if not line:
print("No data received, closing connection.")
break
line = line.decode("utf-8").strip()
if line == "QUIT":
print("Received QUIT command, closing connection.")
break
input_data = line.split()
print(f"Received command: {line}")
output = await command_processor.process(input_data)
if output is None:
response = b"+Error: Command not found\r\n"
elif isinstance(output, str):
response = b"+" + output.encode("utf-8") + b"\r\n"
else:
response = output.encode("utf-8") + b"\r\n"
print(f"Sending response: {response}")
writer.write(response)
await writer.drain()
print("Closing connection.")
writer.close()
await writer.wait_closed()
async def main():
# You can use print statements as follows for debugging, they'll be visible when running tests.
print("Logs from your program will appear here!")
# Uncomment this to pass the first stage
#
server = await asyncio.start_server(handle_connection, host="localhost", port=6379)
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())


