-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkeyvalue_client2.py
64 lines (58 loc) · 1.94 KB
/
keyvalue_client2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from twisted.internet import defer, reactor, protocol
from twisted.protocols import basic
class KeyValueClientProtocol(basic.LineReceiver):
def __init__(self):
self.get_deferreds = []
self.set_deferreds = []
self.delete_deferreds = []
def get(self, key):
self.sendLine('get %s' % key)
d = defer.Deferred()
self.get_deferreds.append(d)
return d
def set(self, key, value):
self.sendLine('set %s %s' % (key, value))
d = defer.Deferred()
self.set_deferreds.append(d)
return d
def delete(self, key):
self.sendLine('delete %s' % key)
d = defer.Deferred()
self.delete_deferreds.append(d)
return d
def lineReceived(self, line):
if line.startswith('VALUE'):
value = line.split()[-1]
d = self.get_deferreds.pop(0)
d.callback(value)
elif line.startswith('STORED'):
key = line.split()[-1]
d = self.set_deferreds.pop(0)
d.callback(key)
elif line.startswith('DELETED'):
key = line.split()[-1]
d = self.delete_deferreds.pop(0)
d.callback(key)
elif line.startswith('DEL_NOT_FOUND'):
key = line.split()[-1]
d = self.delete_deferreds.pop(0)
d.errback(KeyError(key))
elif line.startswith('GET_NOT_FOUND'):
key = line.split()[-1]
d = self.get_deferreds.pop(0)
d.errback(KeyError(key))
if __name__ == '__main__':
def pr(x):
print x
def e(x):
print 'Error:', x.getErrorMessage()
def got_protocol(p):
d = p.set('a', 'value')
d.addCallback(lambda k: p.get('a'))
d.addCallback(pr)
d2 = p.get('b')
d2.addErrback(e)
client = protocol.ClientCreator(reactor, KeyValueClientProtocol)
d = client.connectTCP('localhost', 11211)
d.addCallback(got_protocol)
reactor.run()