Commits

Matt Bone committed b73ea3b

server does some stuff

  • Participants
  • Parent commits 01e2fc5

Comments (0)

Files changed (3)

 Each command needs to be a callable.
 """
 
+from functools import partial
+
 def get(db, key):
     """
     See: http://redis.io/commands/get
     return db.get(key)
 
 
-def set(db, key, value):
+def sset(db, key, value):
     """
     See: http://redis.io/commands/set
     """
 
     return value
 
+
+def ping():
+    return "PONG"
+
+
+class Backend(object):
+
+    def __init__(self):
+        self.db = {}  # should eventually support multiple dbs 
+
+        self.commands =  {
+            'incr': partial(incr, self.db),
+            'decr': partial(decr, self.db),
+            'set': partial(sset, self.db),
+            'get': partial(get, self.db),
+            'ping': ping,
+            
+        }
+
+    
+    def dispatch(self, command, args):
+        return self.commands[command](*args)
 """
-A bloom filter server.
+redis-in-py server
 """
 
 from twisted.internet import protocol, reactor
+from twisted.protocols.basic import LineReceiver
 
-class Echo(protocol.Protocol):
-    def dataReceived(self, data):
-        self.transport.write(data)
+from commands import Backend
 
-class EchoFactory(protocol.Factory):
+
+def coerce_arg(arg):
+    try:
+        arg = int(arg)
+    except ValueError:
+        pass
+    return arg
+
+
+class RedisInPy(LineReceiver):
+    def __init__(self, backend, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+
+        self.backend = backend
+
+    def lineReceived(self, line):
+        split = line.decode().split()
+        result = self.backend.dispatch(split[0].lower(), 
+                                       [coerce_arg(arg) for arg in split[1:]])
+        if result is not None:
+            self.sendLine(str(result).encode())
+
+
+class RedisInPyFactory(protocol.Factory):
+    backend = Backend()
+
     def buildProtocol(self, addr):
-        print(addr)
-        return Echo()
+        return RedisInPy(self.backend)
+
 
 if __name__ == "__main__":
-    reactor.listenTCP(1234, EchoFactory())
+    reactor.listenTCP(1234, RedisInPyFactory())
     reactor.run()

File test_commands.py

-from commands import get, set, incr, decr
+from commands import get, sset, incr, decr
 
 def test_get():
     db = {}
     assert get(db, "foo") == 42
 
 
-def test_set():
+def test_sset():
     db = {}
-    set(db, "foo", 42)
+    sset(db, "foo", 42)
 
     assert db["foo"] == 42