Python zmq.UNSUBSCRIBE Examples

The following are 23 code examples of zmq.UNSUBSCRIBE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zmq , or try the search function .
Example #1
Source File: socket.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_string(self, option, optval, encoding='utf-8'):
        """Set socket options with a unicode object.
        
        This is simply a wrapper for setsockopt to protect from encoding ambiguity.

        See the 0MQ documentation for details on specific options.
        
        Parameters
        ----------
        option : int
            The name of the option to set. Can be any of: SUBSCRIBE, 
            UNSUBSCRIBE, IDENTITY
        optval : unicode string (unicode on py2, str on py3)
            The value of the option to set.
        encoding : str
            The encoding to be used, default is utf8
        """
        if not isinstance(optval, unicode):
            raise TypeError("unicode strings only")
        return self.set(option, optval.encode(encoding)) 
Example #2
Source File: socket.py    From pySINDy with MIT License 6 votes vote down vote up
def set_string(self, option, optval, encoding='utf-8'):
        """Set socket options with a unicode object.
        
        This is simply a wrapper for setsockopt to protect from encoding ambiguity.

        See the 0MQ documentation for details on specific options.
        
        Parameters
        ----------
        option : int
            The name of the option to set. Can be any of: SUBSCRIBE, 
            UNSUBSCRIBE, IDENTITY
        optval : unicode string (unicode on py2, str on py3)
            The value of the option to set.
        encoding : str
            The encoding to be used, default is utf8
        """
        if not isinstance(optval, unicode):
            raise TypeError("unicode strings only")
        return self.set(option, optval.encode(encoding)) 
Example #3
Source File: socket.py    From pySINDy with MIT License 5 votes vote down vote up
def __setattr__(self, key, value):
        """Override to allow setting zmq.[UN]SUBSCRIBE even though we have a subscribe method"""
        _key = key.lower()
        if _key in ('subscribe', 'unsubscribe'):
            
            if isinstance(value, unicode):
                value = value.encode('utf8')
            if _key == 'subscribe':
                self.set(zmq.SUBSCRIBE, value)
            else:
                self.set(zmq.UNSUBSCRIBE, value)
            return
        super(Socket, self).__setattr__(key, value) 
Example #4
Source File: rpc.py    From huobi with MIT License 5 votes vote down vote up
def unsubscribe(self, topic):
        if topic != '':
            topic_ = self.pack(topic)
            self.__subSocket.setsockopt(zmq.UNSUBSCRIBE, topic_)
        else:
            self.__subSocket.unsubscribe('') 
Example #5
Source File: handler.py    From huobi with MIT License 5 votes vote down vote up
def remove_topic(self, topic):
        self.sub_socket.setsockopt(zmq.UNSUBSCRIBE, pickle.dumps(topic))
        self.topic.remove(topic) 
Example #6
Source File: socket.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unsubscribe(self, topic):
        """Unsubscribe from a topic

        Only for SUB sockets.

        .. versionadded:: 15.3
        """
        if isinstance(topic, unicode):
            topic = topic.encode('utf8')
        self.set(zmq.UNSUBSCRIBE, topic) 
Example #7
Source File: socket.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __setattr__(self, key, value):
        """Override to allow setting zmq.[UN]SUBSCRIBE even though we have a subscribe method"""
        _key = key.lower()
        if _key in ('subscribe', 'unsubscribe'):
            
            if isinstance(value, unicode):
                value = value.encode('utf8')
            if _key == 'subscribe':
                self.set(zmq.SUBSCRIBE, value)
            else:
                self.set(zmq.UNSUBSCRIBE, value)
            return
        super(Socket, self).__setattr__(key, value) 
Example #8
Source File: client.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def unsubscribe(self, streamname, node_id=b''):
        ''' Unsubscribe from a stream. '''
        self.stream_in.setsockopt(zmq.UNSUBSCRIBE, streamname + node_id) 
Example #9
Source File: agent.py    From osbrain with Apache License 2.0 5 votes vote down vote up
def unsubscribe(self, alias: str, topic: Union[bytes, str]) -> None:
        """
        Unsubscribe a SUB/SYNC_SUB socket given by its alias from a given
        specific topic, and delete its entry from the handlers dictionary.

        If instead of a single topic, a tuple or a list of topics is passed,
        the agent will unsubscribe from all the supplied topics.
        """
        if isinstance(topic, (tuple, list)):
            for t in topic:
                self.unsubscribe(alias, t)
            return

        topic = topic_to_bytes(topic)

        if isinstance(self._address[alias], AgentAddress):
            self._socket[alias].setsockopt(zmq.UNSUBSCRIBE, topic)
            del self._handler[self._socket[alias]][topic]
        elif isinstance(self._address[alias], AgentChannel):
            channel = self._address[alias]
            sub_address = channel.receiver
            treated_topic = channel.twin_uuid + topic
            self._socket[sub_address].setsockopt(
                zmq.UNSUBSCRIBE, treated_topic
            )
            del self._handler[self._socket[sub_address]][treated_topic]
        else:
            raise NotImplementedError(
                'Unsupported address type %s!' % self._address[alias]
            ) 
Example #10
Source File: DWX_ZeroMQ_Connector_v2_0_1_RC8.py    From DarwinexLabs with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _DWX_MTX_UNSUBSCRIBE_MARKETDATA_(self, _symbol):
        
        self._SUB_SOCKET.setsockopt_string(zmq.UNSUBSCRIBE, _symbol)
        print("\n**\n[KERNEL] Unsubscribing from " + _symbol + "\n**\n") 
Example #11
Source File: socket.py    From pySINDy with MIT License 5 votes vote down vote up
def unsubscribe(self, topic):
        """Unsubscribe from a topic

        Only for SUB sockets.

        .. versionadded:: 15.3
        """
        if isinstance(topic, unicode):
            topic = topic.encode('utf8')
        self.set(zmq.UNSUBSCRIBE, topic) 
Example #12
Source File: socket.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __setattr__(self, key, value):
        """Override to allow setting zmq.[UN]SUBSCRIBE even though we have a subscribe method"""
        _key = key.lower()
        if _key in ('subscribe', 'unsubscribe'):
            
            if isinstance(value, unicode):
                value = value.encode('utf8')
            if _key == 'subscribe':
                self.set(zmq.SUBSCRIBE, value)
            else:
                self.set(zmq.UNSUBSCRIBE, value)
            return
        super(Socket, self).__setattr__(key, value) 
Example #13
Source File: supvisorszmq.py    From supvisors with Apache License 2.0 5 votes vote down vote up
def unsubscribe(self, code):
        """ Remove subscription to the event named code. """
        self.socket.setsockopt(zmq.UNSUBSCRIBE, code.encode('utf-8'))

    # reception part 
Example #14
Source File: supvisorszmq.py    From supvisors with Apache License 2.0 5 votes vote down vote up
def unsubscribe_all(self):
        """ Subscription to all events. """
        self.socket.setsockopt(zmq.UNSUBSCRIBE, '') 
Example #15
Source File: client.py    From testplan with Apache License 2.0 5 votes vote down vote up
def unsubscribe(self, topic_filter):
        """
        Unsubscribe the client from a particular filter. Only for
        SUBSCRIBE clients.

        :param topic_filter: Filter to be removed.
        :type topic_filter: ``str``
        """
        if self.cfg.message_pattern == zmq.SUB:
            self._socket.setsockopt(zmq.UNSUBSCRIBE, topic_filter) 
Example #16
Source File: logwatcher.py    From Computable with MIT License 5 votes vote down vote up
def subscribe(self):
        """Update our SUB socket's subscriptions."""
        self.stream.setsockopt(zmq.UNSUBSCRIBE, '')
        if '' in self.topics:
            self.log.debug("Subscribing to: everything")
            self.stream.setsockopt(zmq.SUBSCRIBE, '')
        else:
            for topic in self.topics:
                self.log.debug("Subscribing to: %r"%(topic))
                self.stream.setsockopt(zmq.SUBSCRIBE, topic) 
Example #17
Source File: DWX_ZeroMQ_Connector_v2_0_2_RC1.py    From dwx-zeromq-connector with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _DWX_MTX_UNSUBSCRIBE_MARKETDATA_(self, _symbol):
        
        self._SUB_SOCKET.setsockopt_string(zmq.UNSUBSCRIBE, _symbol)
        print("\n**\n[KERNEL] Unsubscribing from " + _symbol + "\n**\n") 
Example #18
Source File: DWX_ZeroMQ_Connector_v2_0_1_RC8.py    From dwx-zeromq-connector with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _DWX_MTX_UNSUBSCRIBE_MARKETDATA_(self, _symbol):
        
        self._SUB_SOCKET.setsockopt_string(zmq.UNSUBSCRIBE, _symbol)
        print("\n**\n[KERNEL] Unsubscribing from " + _symbol + "\n**\n") 
Example #19
Source File: core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def set(self, opt, val):
        """set socket option"""
        if opt in TIMEOS:
            warnings.warn("TIMEO socket options have no effect in zmq.green", UserWarning)
        result = super(_Socket, self).set(opt, val)
        if opt in (zmq.SUBSCRIBE, zmq.UNSUBSCRIBE):
            self.__state_changed()
        return result 
Example #20
Source File: test_pubsub.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_sigabrt_issue(self, random=Random(42)):
            import gevent
            pub = self.context.socket(zmq.PUB)
            pub.setsockopt(zmq.LINGER, 0)
            self.sockets.append(pub)
            topics = [str(random.random())[2:] for x in range(10000)]
            def workload(sub):
                subscribed = set()
                # Many subscriptions, for example above 5000, are
                # raising up reproducibility of the crash.
                for x in range(10000):
                    if not subscribed or random.random() < 0.9:
                        topic = random.choice(topics)
                        subscribed.add(topic)
                        sub.set(zmq.SUBSCRIBE, topic)
                    else:
                        topic = random.choice(list(subscribed))
                        subscribed.remove(topic)
                        sub.set(zmq.UNSUBSCRIBE, topic)
                    # Sleeping with gevent for 0 seconds is necessary
                    # to reproduce the crash.
                    gevent.sleep(0)
            for x in range(3):
                sub, addr = self.create_sub()
                pub.connect(addr)
                workload(sub)
                # Only SUB socket closes.  If PUB socket disconnects,
                # the crash won't be reproduced.
                sub.close() 
Example #21
Source File: socket.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def set_string(self, option, optval, encoding='utf-8'):
        """Set socket options with a unicode object.
        
        This is simply a wrapper for setsockopt to protect from encoding ambiguity.

        See the 0MQ documentation for details on specific options.
        
        Parameters
        ----------
        option : int
            The name of the option to set. Can be any of: SUBSCRIBE, 
            UNSUBSCRIBE, IDENTITY
        optval : unicode string (unicode on py2, str on py3)
            The value of the option to set.
        encoding : str
            The encoding to be used, default is utf8
        """
        if not isinstance(optval, unicode):
            raise TypeError("unicode strings only")
        return self.set(option, optval.encode(encoding)) 
Example #22
Source File: socket.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def unsubscribe(self, topic):
        """Unsubscribe from a topic

        Only for SUB sockets.

        .. versionadded:: 15.3
        """
        if isinstance(topic, unicode):
            topic = topic.encode('utf8')
        self.set(zmq.UNSUBSCRIBE, topic) 
Example #23
Source File: controllers.py    From cstar_perf with Apache License 2.0 4 votes vote down vote up
def console_messages(ws):
    """Receive console messages as they happen

    ZMQ message format:
     Console messages:
      console cluster_name {"job_id":"current_job_id", "msg":"message from console"}
     Control messages:
      Keep alive:
      The cluster is starting a job:
       console cluster_name {"job_id":"current_job_id", "ctl":"START"}
      The cluster finished a job:
       console cluster_name {"job_id":"current_job_id", "ctl":"DONE"}
      The cluster is not working on anything:
       console cluster_name {"ctl":"IDLE"}

    When forwarding messages to the websocket client, the "console cluster_name" 
    portion is dropped and just the JSON is sent.

    Websocket sends keepalive messages periodically:
     {"ctl":"KEEPALIVE"}

    """
    cluster_name = ws.receive()
    console_socket = console_subscribe(cluster_name)
    try:
        while True:
            try:
                data = console_socket.recv_string()
                data = data.lstrip("console {cluster_name} ".format(cluster_name=cluster_name))
                ws.send(data)
            except zmq.error.Again:
                # If we timeout from zmq, send a keep alive request to the
                # websocket client:
                ws.send('{"ctl":"KEEPALIVE"}')
                # The client websocket will send keepalive back:
                ws.receive()
            except zmq.error.ZMQError, e:

                if e.errno == zmq.POLLERR:
                    log.error(e)
                    # Interrupted zmq socket code, reinitialize:
                    # I get this when I resize my terminal.. WTF?
                    console_socket = setup_zmq()
    finally:
        log.error("Unsubscribing from zmq socket")
        console_socket.setsockopt_string(zmq.UNSUBSCRIBE, u'')