-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached_client4.py
54 lines (40 loc) · 1.45 KB
/
memcached_client4.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
from twisted.internet import protocol, defer
from memcached_client2 import MemcachedGetProtocol
from memcached_client3 import MemcachedSetProtocol
getFactory = protocol.Factory()
getFactory.protocol = MemcachedGetProtocol
setFactory = protocol.Factory()
setFactory.protocol = MemcachedSetProtocol
class MemcachedClient(object):
def __init__(self, endpoint):
self.endpoint = endpoint
def get(self, key):
deferredValue = defer.Deferred()
d = self.endpoint.connect(getFactory)
def got_protocol(p):
d2 = p.get(key)
def got_response(r):
deferredValue.callback(r)
d2.addCallback(got_response)
d.addCallback(got_protocol)
return deferredValue
def set(self, key, value, flags, timeout=0):
deferredValue = defer.Deferred()
d = self.endpoint.connect(setFactory)
def got_protocol(p):
d2 = p.set(key, value, flags, timeout)
def got_response(r):
deferredValue.callback(r)
d2.addCallback(got_response)
d.addCallback(got_protocol)
return deferredValue
if __name__ == '__main__':
from twisted.internet import reactor, endpoints
endpoint = endpoints.TCP4ClientEndpoint(reactor, '127.0.0.1', 11211)
client = MemcachedClient(endpoint)
d = client.set('a', 'asdf', 0)
def set(_):
print 'SET'
reactor.stop()
d.addCallback(set)
reactor.run()