GET, SET, and the dispatch table
Before the code: what a key-value store actually is
So far the server understands the Redis language but it has nothing to remember. Time to give it a brain. The brain is a Python dictionary that lives in memory, plus a small companion table of timers for keys that should disappear on their own. That is the whole Redis storage model, in plain English. The rest of this module just wires SET, GET, DEL, and EXPIRE into that dictionary.
The store, with and without timers
Quiz: Quiz
Loading practice…
The server has a parser. Now give it a brain. A plain Python dict is your storage. Adding a command means writing a handler with a uniform signature and adding one line to a dispatch table.
STORE: dict[str, str] = {}
def cmd_set(args):
if len(args) < 2:
return encode_error("ERR wrong number of arguments for 'set'")
STORE[args[0]] = args[1]
return encode_simple("OK")
def cmd_get(args):
if len(args) != 1:
return encode_error("ERR wrong number of arguments for 'get'")
return encode_bulk(STORE.get(args[0]))
def cmd_del(args):
deleted = 0
for k in args:
if k in STORE:
del STORE[k]; deleted += 1
return encode_integer(deleted)
COMMANDS = {"SET": cmd_set, "GET": cmd_get, "DEL": cmd_del, ...}STORE is a plain dict. Each command handler takes the args list and returns encoded bytes. COMMANDS is a name->handler map.
Every handler has the same signature: take args, return bytes. That uniformity is what lets the dispatch table work. Adding a new command is one line in COMMANDS plus one function.
A null bulk string: $-1\r\n. redis-cli prints (nil). The -1 length is how RESP distinguishes 'no value' from 'empty string' (which is $0\r\n\r\n).
Matching exercise: Match each RESP shape to what it means
Loading practice…
Quiz: Quiz
Loading practice…