zerorpc支持多个类初始化实战

2018-10-26  本文已影响0人  hugoren

zerorpc官网初始化的例子

class Cooler(object):
    """ Various convenience methods to make things cooler. """

    def add_man(self, sentence):
        """ End a sentence with ", man!" to make it sound cooler, and
        return the result. """
        return sentence + ", man!"

    def add_42(self, n):
        """ Add 42 to an integer argument to make it cooler, and return the
        result. """
        return n + 42

    def boat(self, sentence):
        """ Replace a sentence with "I'm on a boat!", and return that,
        because it's cooler. """
        return "I'm on a boat!"

import zerorpc

s = zerorpc.Server(Cooler())
s.bind("tcp://0.0.0.0:4242")
s.run()

从上看了出来,只能初始化一个类,要是有一些任务场景,需要按资源或多个类初始化呢?

根据源码封装成dict

从zerorpc的源码core.py 74-82行可以看出, 如果methods是dict对象,直接返回;如果是类名,则转化成dict。 所以我们可以直接初始化成dict,而dict是支持n个。

  @staticmethod
    def _filter_methods(cls, self, methods):
        if isinstance(methods, dict):
            return methods
        server_methods = set(k for k in dir(cls) if not k.startswith('_'))
        return dict((k, getattr(methods, k))
                    for k in dir(methods)
                    if callable(getattr(methods, k)) and
                    not k.startswith('_') and k not in server_methods
                    )

server端例子

import zerorpc

_method = {}


def register(cls):
    obj = cls()

    prefix = cls.__name__
    _method.update({'{}:{}'.format(prefix, k): getattr(obj, k)
                     for k in dir(obj)
                     if not k.startswith('_') and callable(getattr(obj, k))})
    return cls


@register
class RpcServer:
    def add(self, x, y):
        return x+y

server = zerorpc.Server(_method, heartbeat=20)
server.bind("tcp://{0}:{1}".format('127.0.0.1', 4242))
server.run()

从上可以看,写法上就是cc core.py的那段

client端

import zerorpc


class Client(zerorpc.Client):
    def __init__(self, *arg, **kwargs):
        self._prefix = kwargs.pop("prefix", "")
        super(Client, self).__init__(*arg, **kwargs)

    def set_prefix(self, prefix):
        self._prefix = prefix

    def __getattr__(self, method):
        method = ":".join([self._prefix, method]) if self._prefix else method
        return lambda *args, **kwargs: self(method, *args, **kwargs)


def client_call():
    print('zerorpc client')
    c = Client(prefix="RpcServer")
    c.connect('tcp://127.0.0.1:4242')
    for i in range(1):
        try:
            r = c.add(4, 5)
            print(r)
        except Exception as e:
            print(e)

看看运行的结果

image.png

参考
https://github.com/0rpc/zerorpc-python
https://zhu327.github.io/2017/05/08/zerorpc-api%E8%AE%BE%E8%AE%A1%E6%8C%87%E5%8D%97/

上一篇 下一篇

猜你喜欢

热点阅读