本文整理汇总了Python中stompest.sync.Stomp.unsubscribe方法的典型用法代码示例。如果您正苦于以下问题:Python Stomp.unsubscribe方法的具体用法?Python Stomp.unsubscribe怎么用?Python Stomp.unsubscribe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stompest.sync.Stomp
的用法示例。
在下文中一共展示了Stomp.unsubscribe方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _test_4_integration_stomp
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def _test_4_integration_stomp(self, version):
client = Stomp(self.getConfig(version))
try:
client.connect(host=VIRTUALHOST, versions=[version])
except StompProtocolError as e:
print('Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % (e, version))
return
client.send(self.DESTINATION, b'test message 1')
client.send(self.DESTINATION, b'test message 2')
self.assertFalse(client.canRead(self.TIMEOUT))
token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertFalse(client.canRead(self.TIMEOUT))
client.unsubscribe(token)
client.send(self.DESTINATION, b'test message 3', receipt='4711')
self.assertTrue(client.canRead(self.TIMEOUT))
self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4711'}))
self.assertFalse(client.canRead(self.TIMEOUT))
client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertFalse(client.canRead(self.TIMEOUT))
client.disconnect(receipt='4712')
self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4712'}))
self.assertRaises(StompConnectionError, client.receiveFrame)
client.connect(host=VIRTUALHOST)
client.disconnect(receipt='4711')
self.assertEqual(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {StompSpec.RECEIPT_ID_HEADER: '4711'}))
client.close()
self.assertRaises(StompConnectionError, client.canRead, 0)
示例2: test_6_integration_stomp_1_1_encoding_and_escaping_headers
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def test_6_integration_stomp_1_1_encoding_and_escaping_headers(self):
if BROKER == 'rabbitmq':
print('Broker does not support unicode characters. Skipping this test case.')
return
version = StompSpec.VERSION_1_1
client = Stomp(self.getConfig(version))
try:
client.connect(host=VIRTUALHOST, versions=[version])
except StompProtocolError as e:
print('Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % (e, version))
return
key = b'fen\xc3\xaatre'.decode('utf-8')
value = b'\xc2\xbfqu\xc3\xa9 tal?'.decode('utf-8')
headers = {key: value}
client.send(self.DESTINATION, body=b'test message 1', headers=headers)
self.assertFalse(client.canRead(self.TIMEOUT))
token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
self.assertTrue(client.canRead(self.TIMEOUT))
frame = client.receiveFrame()
client.ack(frame)
self.assertEqual(frame.version, version)
self.assertEqual(frame.headers[key], headers[key])
self.assertFalse(client.canRead(self.TIMEOUT))
client.unsubscribe(token)
client.disconnect(receipt='4712')
示例3: test_6_integration_stomp_1_1_encoding_and_escaping_headers
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def test_6_integration_stomp_1_1_encoding_and_escaping_headers(self):
if BROKER == 'rabbitmq':
print 'Broker does not support unicode characters. Skipping this test case.'
return
version = StompSpec.VERSION_1_1
client = Stomp(self.getConfig(version))
try:
client.connect(host=VIRTUALHOST, versions=[version])
except StompProtocolError as e:
print 'Broker does not support STOMP protocol %s. Skipping this test case. [%s]' % (e, version)
return
specialCharactersHeader = u'fen\xeatre:\r\n'
headers = {specialCharactersHeader: u'\xbfqu\xe9 tal?, s\xfc\xdf'}
client.send(self.DESTINATION, body='test message 1', headers=headers)
self.assertFalse(client.canRead(self.TIMEOUT))
token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
self.assertTrue(client.canRead(self.TIMEOUT))
frame = client.receiveFrame()
client.ack(frame)
self.assertEquals(frame.version, version)
self.assertEquals(frame.headers[specialCharactersHeader], headers[specialCharactersHeader])
self.assertFalse(client.canRead(self.TIMEOUT))
client.unsubscribe(token)
client.disconnect(receipt='4712')
示例4: test_4_integration_stomp_1_1
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def test_4_integration_stomp_1_1(self):
if StompSpec.VERSION_1_1 not in commands.versions(VERSION):
print 'This broker does not support STOMP protocol version 1.1'
return
client = Stomp(self.getConfig(StompSpec.VERSION_1_1))
client.connect(host=VIRTUALHOST)
client.send(self.DESTINATION, 'test message 1')
client.send(self.DESTINATION, 'test message 2')
self.assertFalse(client.canRead(self.TIMEOUT))
token = client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: 'client-individual'})
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertFalse(client.canRead(self.TIMEOUT))
client.unsubscribe(token)
client.send(self.DESTINATION, 'test message 3', receipt='4711')
self.assertTrue(client.canRead(self.TIMEOUT))
self.assertEquals(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {'receipt-id': '4711'}))
self.assertFalse(client.canRead(self.TIMEOUT))
client.subscribe(self.DESTINATION, {StompSpec.ID_HEADER: 4711, StompSpec.ACK_HEADER: 'client-individual'})
self.assertTrue(client.canRead(self.TIMEOUT))
client.ack(client.receiveFrame())
self.assertFalse(client.canRead(self.TIMEOUT))
client.disconnect(receipt='4712')
self.assertEquals(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {'receipt-id': '4712'}))
self.assertRaises(StompConnectionError, client.receiveFrame)
client.connect(host=VIRTUALHOST)
client.disconnect(receipt='4711')
self.assertEquals(client.receiveFrame(), StompFrame(StompSpec.RECEIPT, {'receipt-id': '4711'}))
client.close()
self.assertRaises(StompConnectionError, client.canRead, 0)
示例5: call_route
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def call_route(request_queue, response_queue, request):
"""
"""
config = {
"stomp": {
"server": '192.168.0.3',
"port": 61613,
"timeout": 15,
}
}
stomp_config = StompConfig("tcp://%s:%d" % (config['stomp']['server'], config['stomp']['port']), version=StompSpec.VERSION_1_0)
stomp = Stomp(stomp_config)
stomp.connect()
jms_id = str(uuid4())
token = stomp.subscribe(response_queue, {'JMSCorrelationID': jms_id})
stomp.send(request_queue, json.dumps(request), {'JMSCorrelationID': jms_id})
response = None
if stomp.canRead(config['stomp']['timeout']):
response = stomp.receiveFrame()
stomp.unsubscribe(token)
return response
示例6: test_3_socket_failure_and_replay
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
def test_3_socket_failure_and_replay(self):
client = Stomp(self.getConfig(StompSpec.VERSION_1_0))
client.connect(host=VIRTUALHOST)
headers = {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}
token = client.subscribe(self.DESTINATION, headers)
client.sendFrame(StompFrame(StompSpec.DISCONNECT)) # DISCONNECT frame is out-of-band, as far as the session is concerned -> unexpected disconnect
self.assertRaises(StompConnectionError, client.receiveFrame)
client.connect(host=VIRTUALHOST)
client.send(self.DESTINATION, b'test message 1')
client.ack(client.receiveFrame())
client.unsubscribe(token)
headers = {StompSpec.ID_HEADER: 'bla', StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL}
client.subscribe(self.DESTINATION, headers)
headers[StompSpec.DESTINATION_HEADER] = self.DESTINATION
client.sendFrame(StompFrame(StompSpec.DISCONNECT)) # DISCONNECT frame is out-of-band, as far as the session is concerned -> unexpected disconnect
self.assertRaises(StompConnectionError, client.receiveFrame)
client.connect(host=VIRTUALHOST)
client.send(self.DESTINATION, b'test message 2')
client.ack(client.receiveFrame())
client.unsubscribe((StompSpec.ID_HEADER, 'bla'))
client.disconnect()
示例7: StompClient
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
#.........这里部分代码省略.........
def send_heartbeat(self, event):
if self.connected:
LOG.debug("Sending heartbeat")
try:
self._client.beat()
except StompConnectionError:
event.success = False
self.fire(disconnected())
@handler("generate_events")
def generate_events(self, event):
if not self.connected:
return
try:
if self._client.canRead(1):
frame = self._client.receiveFrame()
LOG.debug("Recieved frame %s", frame)
self.fire(message(frame))
except StompConnectionError:
self.fire(disconnected())
@handler("send")
def send(self, event, destination, body, headers=None, receipt=None):
LOG.debug("send()")
if not self.connected:
LOG.error("Can't send when Stomp is disconnected")
self.fire(on_stomp_error(None, Exception("Message send attempted with stomp disconnected")))
event.success = False
return
try:
self._client.send(destination, body=body.encode('utf-8'), headers=headers, receipt=receipt)
LOG.debug("Message sent")
except StompConnectionError as err:
event.success = False
self.fire(disconnected())
except StompError as err:
LOG.error("Error sending ack")
event.success = False
self.fire(on_stomp_error(None, err))
@handler("subscribe")
def _subscribe(self, event, destination, ack=ACK_CLIENT_INDIVIDUAL):
if ack not in ACK_MODES:
raise ValueError("Invalid client ack mode specified")
LOG.info("Subscribe to message destination %s", destination)
try:
# Set ID to match destination name for easy reference later
frame, token = self._client.subscribe(destination,
headers={StompSpec.ACK_HEADER: ack,
'id': destination})
self._subscribed[destination] = token
except StompConnectionError as err:
event.success = False
self.fire(disconnected())
except StompError as err:
event.success = False
LOG.debug(traceback.format_exc())
self.fire(on_stomp_error(None, err))
@handler("unsubscribe")
def _unsubscribe(self, event, destination):
if destination not in self._subscribed:
LOG.error("Unsubscribe Request Ignored. Not subscribed to %s", destination)
return
try:
token = self._subscribed.pop(destination)
frame = self._client.unsubscribe(token)
LOG.debug("Unsubscribed: %s", frame)
except StompConnectionError as err:
event.success = False
self.fire(disconnected())
except StompError as err:
LOG.error("Error sending ack")
event.success = False
self.fire(on_stomp_error(frame, err))
@handler("message")
def on_message(self, event, headers, message):
LOG.info("Stomp message received")
@handler("ack")
def ack_frame(self, event, frame):
LOG.debug("ack_frame()")
try:
self._client.ack(frame)
LOG.debug("Ack Sent")
except StompConnectionError as err:
LOG.error("Error sending ack")
event.success = False
self.fire(disconnected())
except StompError as err:
LOG.error("Error sending ack")
event.success = False
self.fire(on_stomp_error(frame, err))
def get_subscription(self, frame):
""" Get subscription from frame """
LOG.info(self._subscribed)
_, token = self._client.message(frame)
return self._subscribed[token]
示例8: JMSClient
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
#.........这里部分代码省略.........
"""
try:
msg = 'destination_name:{0}, count:{1}'.format(
destination_name, cnt)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_jms_receiving_msg', msg), self._mh.fromhere())
if (not self._is_connected):
self._mh.demsg('htk_on_warning', self._mh._trn.msg(
'htk_jms_not_connected'), self._mh.fromhere())
return None
ev = event.Event('jms_before_receive', destination_name, cnt)
if (self._mh.fire_event(ev) > 0):
destination_name = ev.argv(0)
cnt = ev.argv(1)
if (ev.will_run_default()):
token = self._client.subscribe('/queue/{0}'.format(destination_name),
{StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
msgs = []
i = 0
while (i < cnt and self._client.canRead(1)):
frame = self._client.receiveFrame()
if (frame.command != 'MESSAGE'):
break
self._client.ack(frame)
msgs.append(frame)
i = i + 1
self._client.unsubscribe(token)
messages = []
for msg in msgs:
message = {}
message['message'] = msg.body.decode()
for header in msg.rawHeaders:
if (header[0] in mapping.values()):
message[
list(mapping.keys())[list(mapping.values()).index(header[0])]] = header[1]
messages.append(message)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_jms_msg_received', len(messages)), self._mh.fromhere())
ev = event.Event('jms_after_receive')
self._mh.fire_event(ev)
return messages
except StompError as ex:
self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
return None
def browse(self, destination_name, cnt=100, jms_correlation_id=None, jms_type=None):
"""Method browses queue
Args:
destination_name (str): queue name
cnt (int): count of messages
jms_correlation_id (str): requested JMSCorrelationID
jms_type (str): requested JMSType
示例9: ByteportStompClient
# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import unsubscribe [as 别名]
class ByteportStompClient(AbstractByteportClient):
DEFAULT_BROKER_HOST = 'stomp.byteport.se'
STORE_QUEUE_NAME = '/queue/simple_string_dev_message'
SUPPORTED_CHANNEL_TYPES = ['topic', 'queue']
client = None
def __init__(self, namespace, login, passcode, broker_host=DEFAULT_BROKER_HOST, device_uid=None, channel_type='topic'):
'''
Create a ByteportStompClient. This is a thin wrapper to the underlying STOMP-client that connets to the Byteport Broker
If a device_uid is given, a subscription will be made for Messages sent through Byteport.
The channel_type must be either 'topic' or 'queue'. Set top topic if unsure on what to use (use queue if you need to
use multiple consumers for a single device, this is not how most applications are set up).
:param namespace:
:param login: Broker username (Byteport web users are _not_ valid broker users). Ask [email protected] for access.
:param passcode: Broker passcode
:param broker_hosts: [optional] A list of brokers to connect to
:param device_uid: [optional] The device UID to subscribe for messages on
:param channel_type: [optional] Defaults to queue.
:param channel_key: [optional] Must match the configured key in the Byteport Device Manager
'''
self.namespace = str(namespace)
self.device_uid = device_uid
if channel_type not in self.SUPPORTED_CHANNEL_TYPES:
raise Exception("Unsupported channel type: %s" % channel_type)
broker_url = 'tcp://%s:61613' % broker_host
self.CONFIG = StompConfig(broker_url, version=StompSpec.VERSION_1_2)
self.client = Stomp(self.CONFIG)
try:
self.client.connect(headers={'login': login, 'passcode': passcode}, host='/')
logging.info("Connected to Stomp broker at %s using protocol version %s" % (broker_host, self.client.session.version))
# Set up a subscription on the correct queue if a Specific device UID was given
if self.device_uid:
subscribe_headers = dict()
subscribe_headers[StompSpec.ACK_HEADER] = StompSpec.ACK_CLIENT_INDIVIDUAL
subscribe_headers[StompSpec.ID_HEADER] = '0'
device_message_queue_name = '/%s/device_messages_%s.%s' % (channel_type, namespace, device_uid)
self.subscription_token = self.client.subscribe(device_message_queue_name, subscribe_headers)
logging.info("Subscribing to channel %s" % device_message_queue_name)
except StompProtocolError as e:
logging.error("Client socket connected, but probably failed to login. (ProtocolError)")
raise
except StompConnectionError:
logging.error("Failed to connect to Stomp Broker at %s" % broker_host)
raise
def disconnect(self):
if self.subscription_token:
try:
self.client.unsubscribe(self.subscription_token)
except Exception as e:
logging.error(u'Unsubscribe failed, reason %s' % e)
self.client.disconnect()
def __send_json_message(self, json):
self.client.send(self.STORE_QUEUE_NAME, json)
def __send_message(self, uid, data_string, timestamp=None):
if timestamp:
timestamp = self.auto_timestamp(timestamp)
else:
timestamp = int(time.time())
if not uid:
uid = self.device_uid
if not uid:
raise Exception("Can not send data without valid Device UID!")
message = dict()
message['uid'] = str(uid)
message['namespace'] = self.namespace
message['data'] = str(data_string)
message['timestamp'] = str(timestamp)
self.__send_json_message(json.dumps([message]))
def store(self, data=None, device_uid=None, timestamp=None):
if type(data) != dict:
raise ByteportClientException("Data must be of type dict")
for key in data.keys():
self.verify_field_name(key)
delimited_data = ';'.join("%s=%s" % (key, self.utf8_encode_value(val)) for (key, val) in data.iteritems())
#.........这里部分代码省略.........