Esempio n. 1
0
class RPCClient():
    """
    事件 rpc 客户端
    """

    endpoint = f'tcp://{settings.RPC_HOST}:{settings.RPC_PORT}'

    def __init__(self):
        """
        初始化
        """
        self._client = Client()

    def __getattr__(self, item):
        """
        设置调用传递到客户端
        """
        return getattr(self._client, item)

    def __enter__(self):
        """
        进入自动连接
        """
        self._client.connect(self.endpoint)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        退出时自动断开,并重置客户端
        """
        self._client.close()
Esempio n. 2
0
class SubscriberAPI():
    def __init__(self, client_ip):
        # Setup pusher service
        self.client = Client()
        self.client.connect(client_ip)

        # print(self.pusher.load_data("TEST"))

        # Connect to message hub
        self._hub = Hub()

        self._hub.subscribe(Message.LoadData, self.client.load_data, self)

    def data_loaded(self, data):
        import msgpack

        unpacked_data = msgpack.unpackb(data)

        self._hub.publish(Message.AddData, unpacked_data)

    def data_unloaded(self, data):
        pass

    def testing(self, msg):
        print("Received 'testing' call on subscriber")
Esempio n. 3
0
 def __init__(self):
     """
     初始化
     """
     self._client = Client()
     self._lock = Lock()
     self._enter_num = 0
Esempio n. 4
0
 def __init__(self, name):
     location = _SERVICES_LOC.get(name)
     if location is not None:
         self.client = Client()
         self.client.connect(location)
     else:
         # direct import
         self.client = None
         self._mod = imp.load_module(name, *imp.find_module(name))
Esempio n. 5
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     """
     退出时自动断开,并重置客户端
     """
     with self._lock:
         self._enter_num -= 1
         if self._enter_num == 0:
             self._client.close()
     self._client = Client()
Esempio n. 6
0
def dotest(peers):
    for p in peers:
        print p['host_string'][p['host_string'].index('@')+1:], p['port']
        c = Client('tcp://{hostname}:{port}'.format(hostname=p['host_string'][p['host_string'].index('@')+1:],
                                                    port=p['port']), timeout=None, heartbeat=None)
        try:
            c.test('test')
        except:
            traceback.print_exc()
Esempio n. 7
0
 def __enter__(self):
     """
     当进入的线程为 0 时,重置客户端并自动连接
     """
     with self._lock:
         if self._enter_num == 0:
             self._client = Client()
             self._client.connect(self.endpoint)
         self._enter_num += 1
     return self
Esempio n. 8
0
    def __init__(self, client_ip):
        # Setup pusher service
        self.client = Client()
        self.client.connect(client_ip)

        # print(self.pusher.load_data("TEST"))

        # Connect to message hub
        self._hub = Hub()

        self._hub.subscribe(Message.LoadData, self.client.load_data, self)
Esempio n. 9
0
class RemoteVault(Vault):
    """Concrete implementation of the class respresenting the remote vault
    interface."""
    def __init__(self, location):
        self.client = Client()
        self.client.connect(location)

    def get(self, id):
        try:
            return self.client.get(id)
        except RemoteError, e:
            raise EXCEPTION_MAP[e.name]() if e.name in EXCEPTION_MAP else e
Esempio n. 10
0
def monitor_zerorpc(peers):
    for p in peers:
        print p['host_string'][p['host_string'].index('@')+1:], p['port'],
        c = Client('tcp://{hostname}:{port}'.format(hostname=p['host_string'][p['host_string'].index('@')+1:],
                                                    port=p['port']), timeout=60, heartbeat=None)
        try:
            c.test('test')
        except RemoteError:
            print 'passed'
        except TimeoutExpired:
            with settings(host_string=p['host_string'], warn_only=True):
                run('kill $(sudo lsof -t -i:{0})'.format(p['port']))
Esempio n. 11
0
class RemoteVault(Vault):
    """Concrete implementation of the class respresenting the remote vault
    interface."""
    def __init__(self, location):
        self.client = Client()
        self.client.connect(location)

    def get(self, id):
        try:
            return self.client.get(id)
        except RemoteError, e:
            raise EXCEPTION_MAP[e.name]() if e.name in EXCEPTION_MAP else e
Esempio n. 12
0
class SubscriberAPI():
    def __init__(self, client_ip):
        # Setup pusher service
        self.client = Client()
        self.client.connect(client_ip)

    def data_loaded(self, data):
        import msgpack

        unpacked_data = msgpack.unpackb(data)

    def data_unloaded(self, data):
        pass

    def testing(self, msg):
        print("Received 'testing' call on subscriber")
Esempio n. 13
0
 def __init__(self, name):
     location = _SERVICES_LOC.get(name)
     if location is not None:
         self.client = Client()
         self.client.connect(location)
     else:
         # direct import
         self.client = None
         self._mod = imp.load_module(name, *imp.find_module(name))
Esempio n. 14
0
def main():
    dbServer = Client()
    dbServer.connect('tcp://127.0.0.1:8000')
    app = Sanic()

    @app.route('/stats/distrib')
    async def distrib(request):
        potatoes = dbServer.get_all_potatoes()
        pie_chart = pygal.Pie()
        for potato in potatoes:
            pie_chart.add(potato['type'], int(potato['count']))

        return HTTPResponse(
            body_bytes=pie_chart.render(),
            status=200,
            headers=None,
            content_type="image/svg+xml")

    app.run(host="0.0.0.0", port=9000)
Esempio n. 15
0
class ThreadingRPCClient(metaclass=SingletonMeta):
    """
    多线程安全的事件 rpc 客户端
    """

    endpoint = f'tcp://{settings.RPC_HOST}:{settings.RPC_PORT}'

    def __init__(self):
        """
        初始化
        """
        self._client = Client()
        self._lock = Lock()
        self._enter_num = 0

    def __getattr__(self, item):
        """
        设置调用传递到客户端
        """
        return getattr(self._client, item)

    def __enter__(self):
        """
        当进入的线程为 0 时,重置客户端并自动连接
        """
        with self._lock:
            if self._enter_num == 0:
                self._client = Client()
                self._client.connect(self.endpoint)
            self._enter_num += 1
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        退出时自动断开,并重置客户端
        """
        with self._lock:
            self._enter_num -= 1
            if self._enter_num == 0:
                self._client.close()
        self._client = Client()
Esempio n. 16
0
def index():

    mqtt_client = Client()
    mqtt_client.connect('tcp://127.0.0.1:2048')
    if not request.args:
        return "未传token"
    else:
        token = request.args.get('token').encode()
        str_token = token.decode('utf-8')
        action = request.get_json()
        print(action)

    sql_data = json.dumps(SearrchORM.select_user(str_token))
    print(sql_data)
    # 鉴权
    certify_token(key=sql_data, token=token)

    # 调用下发指令
    print(mqtt_client.dispatch_action('lua/test/data/456', action))
    # response
    return template_jsonify({})
Esempio n. 17
0
class Service(object):
    def __init__(self, name):
        location = _SERVICES_LOC.get(name)
        if location is not None:
            self.client = Client()
            self.client.connect(location)
        else:
            # direct import
            self.client = None
            self._mod = imp.load_module(name, *imp.find_module(name))

    def __getattr__(self, name):
        return self._runner(name)

    def _runner(self, name):
        def __runner(*args):
            if self.client is not None:
                return self.client(name, *args)
            else:
                return getattr(self._mod, name)(*args)
        return __runner
Esempio n. 18
0
class Service(object):
    def __init__(self, name):
        location = _SERVICES_LOC.get(name)
        if location is not None:
            self.client = Client()
            self.client.connect(location)
        else:
            # direct import
            self.client = None
            self._mod = imp.load_module(name, *imp.find_module(name))

    def __getattr__(self, name):
        return self._runner(name)

    def _runner(self, name):
        def __runner(*args):
            if self.client is not None:
                return self.client(name, *args)
            else:
                return getattr(self._mod, name)(*args)

        return __runner
Esempio n. 19
0
class RPCClient(object):
    def __init__(self, app_id, app_secret, endpoint):
        self.app_id = app_id
        self.app_secret = app_secret
        self.endpoint = endpoint

    def call_old(self,
                 access_token='',
                 method='',
                 path=(),
                 params={},
                 async=False):
        self.client = Client(heartbeat=60, timeout=60)
        self.client.connect(self.endpoint)
        res = self.client.call(self.app_id,
                               self.app_secret,
                               access_token,
                               method,
                               path,
                               params,
                               async=async)
Esempio n. 20
0
 def __init__(self, location):
     self.client = Client()
     self.client.connect(location)
Esempio n. 21
0
 def __init__(self, client_ip):
     # Setup pusher service
     self.client = Client()
     self.client.connect(client_ip)
Esempio n. 22
0
 def __init__(self, location):
     self.client = Client()
     self.client.connect(location)
Esempio n. 23
0
 def __init__(self):
     """
     初始化
     """
     self._client = Client()
Esempio n. 24
0
# -*- coding: utf-8 -*-

from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity

from json import dumps
from zerorpc import Client

c = Client()
c.connect('tcp://127.0.0.1:4242')

class EchoLayer(YowInterfaceLayer):

    @ProtocolEntityCallback('message')
    def onMessage(self, messageProtocolEntity):
        if True:
            self.toLower(OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant()))
            self.toLower(TextMessageProtocolEntity(c.input(self.out(messageProtocolEntity)), to = messageProtocolEntity.getFrom()))

    @ProtocolEntityCallback('receipt')
    def onReceipt(self, entity):
        self.toLower(OutgoingAckProtocolEntity(entity.getId(), 'receipt', entity.getType(), entity.getFrom()))

    def out(self, messageProtocolEntity):
        """
        Retorna la información de los mensajes recibidos en formato json
        """
        out = {
            'name': messageProtocolEntity.getNotify(),
Esempio n. 25
0
# -*- coding: utf-8 -*-

from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback
from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity

from json import dumps
from zerorpc import Client

c = Client()
c.connect('tcp://127.0.0.1:4242')


class EchoLayer(YowInterfaceLayer):
    @ProtocolEntityCallback('message')
    def onMessage(self, messageProtocolEntity):
        if True:
            self.toLower(
                OutgoingReceiptProtocolEntity(
                    messageProtocolEntity.getId(),
                    messageProtocolEntity.getFrom(), 'read',
                    messageProtocolEntity.getParticipant()))
            self.toLower(
                TextMessageProtocolEntity(c.input(
                    self.out(messageProtocolEntity)),
                                          to=messageProtocolEntity.getFrom()))

    @ProtocolEntityCallback('receipt')
    def onReceipt(self, entity):
        self.toLower(