Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# ZeroRPC server/client
2from logging import getLogger
3import threading
4import functools
5import zerorpc
7from ..client import ClientIf
8from ..server import ServerIf
10log = getLogger(__name__)
13class ZeroServer(zerorpc.Server):
14 def __call__(self, method, *args):
15 log.debug("call %s, args=%s", method, args)
16 try:
17 return super().__call__(self, method, *args)
18 except NameError:
19 log.debug("call dispatch %s", method)
20 return self._dispatch(method, args)
23class MyDict(dict):
24 def __init__(self, d, kv):
25 self.d = d
26 self.kv = kv
28 def do_call(self, method, *params, **kwargs):
29 log.debug("calls: %s param=%s, kwargs=%s", method, params, kwargs)
30 return self.d(method, *params)
32 def __hasattr__(self, k):
33 return k in self.kv
35 def get(self, k, defval):
36 try:
37 return self.kv[k]
38 except KeyError:
39 log.debug("get %s def=%s", k, defval)
40 res = functools.partial(self.do_call, k)
41 setattr(res, "__name__", k)
42 log.debug("return: %s", res)
43 return zerorpc.decorators.rep(res)
46class Server(ServerIf):
47 def serve(self, dispatcher):
48 log.debug("start server %s:%s", self.addr_parsed.hostname,
49 self.addr_parsed.port)
50 srv = ZeroServer()
51 # srv._dispatch = dispatcher
52 srv._methods = MyDict(dispatcher, srv._methods)
53 srv.bind("tcp://%s:%s" %
54 (self.addr_parsed.hostname, self.addr_parsed.port))
55 log.debug("methods: %s", srv._methods)
56 srv.run()
59class Client(ClientIf):
60 def __init__(self, addr: str, params: dict = {}):
61 super().__init__(addr, params)
62 self.tl = threading.local()
64 def call(self, method: str, params=None):
65 log.debug("start client %s:%s", self.addr_parsed.hostname,
66 self.addr_parsed.port)
67 if not hasattr(self.tl, "cl"):
68 log.debug("create client")
69 self.tl.cl = zerorpc.Client()
70 self.tl.cl.connect("tcp://%s:%s" %
71 (self.addr_parsed.hostname, self.addr_parsed.port))
72 return self.tl.cl(method, params)