当前位置: 首页>>代码示例>>Python>>正文


Python ServiceBusService.receive_subscription_message方法代码示例

本文整理汇总了Python中azure.servicebus.ServiceBusService.receive_subscription_message方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceBusService.receive_subscription_message方法的具体用法?Python ServiceBusService.receive_subscription_message怎么用?Python ServiceBusService.receive_subscription_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在azure.servicebus.ServiceBusService的用法示例。


在下文中一共展示了ServiceBusService.receive_subscription_message方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: AzureWorker

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
class AzureWorker(Thread):
    def __init__(self):
        Thread.__init__(self)
        self._quit = Event()

        settings = Settings()
        settings.configure_logging('../logs/task_manager.log', 'TaskManagerAzureWorker')

        self.job_manager_url = 'http://' + settings.job_manager_api_connect + ':5000'

        self.unfinished = []
        self.finished = []
        self.executor = Executor(self.unfinished, self.finished)

        self.outgoing_topic = 'finished_jobs'
        self.incoming_topic = 'pending_jobs'

        self.bus_service = ServiceBusService(
            service_namespace=settings.azure_topic_namespace,
            shared_access_key_name=settings.azure_topic_keyname,
            shared_access_key_value=settings.azure_topic_key
        )
        self.bus_service.create_topic(self.incoming_topic)
        self.bus_service.create_topic(self.outgoing_topic)
        self.incoming_topic_subscription = 'AllMessages'
        self.bus_service.create_subscription(self.incoming_topic, self.incoming_topic_subscription)

    def quit(self):
        self._quit.set()

    def run(self):
        self.executor.start()

        # dislike of unstoppable threads
        while not self._quit.is_set():
            msg = self.bus_service.receive_subscription_message(self.incoming_topic, self.incoming_topic_subscription,
                                                                peek_lock=True)
            if msg.body is not None:
                # New job for us!
                job_id = msg.custom_properties['job_id']
                logging.info('getting job with id: ' + job_id + ' from the API')

                r = requests.get(self.job_manager_url + '/jobs/' + job_id)
                job = r.json()

                msg.delete()

                logging.info('appending tasks from job with id: ' + job['id'] + ' and name: ' + job['name'])
                self.unfinished.append(job['name'])

            sleep(3)

        # stop executor
        self.executor.quit()
        self.executor.join()
开发者ID:witlox,项目名称:cumulonimbi,代码行数:57,代码来源:azureworker.py

示例2: AzureBroker

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
class AzureBroker(Thread):
    def __init__(self):
        Thread.__init__(self)
        self._quit = Event()
        self.daemon = True
        self.log = logging.getLogger(__name__)

        self.outgoing_topic = 'pending_jobs'
        self.incoming_topic = 'finished_jobs'
        self.notification_topic = 'jobs_changed'
        self.subscription = 'AllMessages'

        settings = Settings()
        self.bus_service = ServiceBusService(
            service_namespace=settings.azure_topic_namespace,
            shared_access_key_name=settings.azure_topic_keyname,
            shared_access_key_value=settings.azure_topic_key
        )

        self.bus_service.create_topic(self.incoming_topic)
        self.bus_service.create_topic(self.outgoing_topic)
        self.bus_service.create_topic(self.notification_topic)
        self.bus_service.create_subscription(self.incoming_topic, self.subscription)

    def run(self):
        # dislike of unstoppable threads
        while not self._quit.is_set():
            msg = self.bus_service.receive_subscription_message(self.incoming_topic, self.subscription,
                                                                peek_lock=False, timeout=0.1)
            if msg.body is not None:
                self.log.info(msg.body + ":" + msg.custom_properties['job_id'])
                notification_msg = Message('Finished'.encode('utf-8'), custom_properties={'job_id': msg.custom_properties['job_id']})
                self.bus_service.send_topic_message(self.notification_topic, notification_msg)

            sleep(3)

    def transmit_job_created(self, job_id):
        msg = Message('Created'.encode('utf-8'), custom_properties={'job_id': job_id})
        self.bus_service.send_topic_message(self.outgoing_topic, msg)
        self.bus_service.send_topic_message(self.notification_topic, msg)

        self.log.info("Adding job " + job_id + " created to service bus.")

    def transmit_job_assigned(self, job_id, machine_id):
        msg = Message('Assigned'.encode('utf-8'), custom_properties={'job_id': job_id, 'machine_id': machine_id})
        self.bus_service.send_topic_message(self.outgoing_topic, msg)
        self.bus_service.send_topic_message(self.notification_topic, msg)

        self.log.info("Adding job " + job_id + " assigned to " + machine_id + " to the service bus.")

    def quit(self):
        self._quit.set()
开发者ID:witlox,项目名称:cumulonimbi,代码行数:54,代码来源:azurebroker.py

示例3: AzureListener

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
class AzureListener(Thread):
    def __init__(self, machine_manager_logic):
        Thread.__init__(self)
        self._quit = Event()
        self.daemon = True
        self.log = logging.getLogger(__name__)
        self.notification_topic = 'jobs_changed'
        self.subscription = 'AllMessages'
        self.machine_manager_logic = machine_manager_logic

        settings = Settings()
        self.bus_service = ServiceBusService(
            service_namespace=settings.azure_topic_namespace,
            shared_access_key_name=settings.azure_topic_keyname,
            shared_access_key_value=settings.azure_topic_key
        )
        self.bus_service.create_topic(self.notification_topic)
        self.bus_service.create_subscription(self.notification_topic, self.subscription)

    def quit(self):
        self._quit.set()

    def run(self):
        # dislike of unstoppable threads
        while not self._quit.is_set():
            msg = self.bus_service.receive_subscription_message(self.notification_topic, self.subscription,
                                                                peek_lock=False, timeout=0.1)
            if msg.body is not None:
                self.log.info(msg.body + ":" + json.dumps(msg.custom_properties))

                if "Created" in msg.body:
                    self.machine_manager_logic.job_added(msg.custom_properties['job_id'])

                if "Assigned" in msg.body:
                    self.machine_manager_logic.job_assigned(msg.custom_properties['job_id'], msg.custom_properties['machine_id'])

                if "Finished" in msg.body:
                    self.machine_manager_logic.job_removed(msg.custom_properties['job_id'])

            self.machine_manager_logic.check_machines()
            sleep(10)
开发者ID:witlox,项目名称:cumulonimbi,代码行数:43,代码来源:azurelistener.py

示例4: ServiceBusTest

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]

#.........这里部分代码省略.........

    def test_delete_rule_with_non_existing_rule(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')

        # Act
        deleted = self.sbs.delete_rule(
            self.topic_name, 'MySubscription', 'NonExistingRule')

        # Assert
        self.assertFalse(deleted)

    def test_delete_rule_with_non_existing_rule_fail_not_exist(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')

        # Act
        with self.assertRaises(WindowsAzureError):
            self.sbs.delete_rule(
                self.topic_name, 'MySubscription', 'NonExistingRule', True)

        # Assert

    def test_send_topic_message(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')
        sent_msg = Message('subscription message')

        # Act
        self.sbs.send_topic_message(self.topic_name, sent_msg)

        # Assert

    def test_receive_subscription_message_read_delete_mode(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')
        sent_msg = Message('subscription message')
        self.sbs.send_topic_message(self.topic_name, sent_msg)

        # Act
        received_msg = self.sbs.receive_subscription_message(
            self.topic_name, 'MySubscription', False)

        # Assert
        self.assertIsNotNone(received_msg)
        self.assertEquals(sent_msg.body, received_msg.body)

    def test_receive_subscription_message_read_delete_mode_throws_on_delete(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')
        sent_msg = Message('subscription message')
        self.sbs.send_topic_message(self.topic_name, sent_msg)

        # Act
        received_msg = self.sbs.receive_subscription_message(
            self.topic_name, 'MySubscription', False)
        with self.assertRaises(WindowsAzureError):
            received_msg.delete()

        # Assert

    def test_receive_subscription_message_read_delete_mode_throws_on_unlock(self):
        # Arrange
        self._create_topic_and_subscription(self.topic_name, 'MySubscription')
        sent_msg = Message('subscription message')
        self.sbs.send_topic_message(self.topic_name, sent_msg)
开发者ID:slick666,项目名称:azure-sdk-for-python,代码行数:70,代码来源:test_servicebusservice.py

示例5: Client

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
class Client(object):
    """Client for ServiceBusService"""

    def __init__(self, sbs_namespace, sbs_access_key):
        if not sbs_namespace:
            raise ValueError("'sbs_namespace' is required")

        if not sbs_access_key:
            raise ValueError("'sbs_access_key' is required")

        self._logger = logging.getLogger(__name__)
        self._sbs = ServiceBusService(service_namespace=sbs_namespace,
                                      shared_access_key_name=SBS_KEY_NAME,
                                      shared_access_key_value=sbs_access_key)
        self._stop_event = None
        self._thread = None
        self._last_sequence = None

    def start(self):
        """starts subscription"""
        if not self._thread is None:
            raise Exception("Client already started")

        self._logger.info("Starting client for host %s", self._sbs._get_host())
        self._stop_event = threading.Event()
        self._thread = threading.Thread(target=self._receive_messages)
        self._thread.daemon = True
        self._thread.start()


    def stop(self):
        """stops subscription"""
        if self._thread is None:
            raise Exception("Client is not started")

        self._logger.info("Stopping client. May take up to %d seconds", MESSAGE_WAIT_TIMEOUT)
        self._stop_event.set()
        self._thread.join()
        self._thread = None
        self._stop_event = None
        self._logger.info("Client stopped")

    def _receive_messages(self):
        """Receieves messages from service"""
        while not self._stop_event.is_set():
            try:
                message = self._sbs.receive_subscription_message(SBS_TOPIC_NAME,
                                                                 SBS_SUBSCRIPTION_NAME,
                                                                 timeout=MESSAGE_WAIT_TIMEOUT,
                                                                 peek_lock=False)
            except Exception:
                self._logger.exception("Error while pulling message from topic")
                self._stop_event.wait(MESSAGE_WAIT_AFTER_ERROR)
                continue

            if message is None or message.body is None:
                self._logger.debug("No message received after waiting %d seconds",
                                   MESSAGE_WAIT_TIMEOUT)
            else:
                sequence = message.broker_properties[u'SequenceNumber']
                sent_on = message.broker_properties[u'EnqueuedTimeUtc']
                body = message.body
                self._logger.info("Message with sequence '%s' sent on '%s' receieved: %s",
                                  sequence, sent_on, body)
                if self._last_sequence > sequence:
                    self._logger.warning("Skipping message with sequence '%s' because the later"\
                                         " one with sequence '%s' was already processed",
                                         sequence, self._last_sequence)
                else:
                    self._last_sequence = sequence
                    try:
                        self._process_message(body)
                    except Exception:
                        self._logger.exception("Failed to process a message")


    def _process_message(self, message_body):
        """Process single message"""
        parsed_message = json.loads(message_body)
        msg_sender = parsed_message[u'name']
        msg_text = parsed_message[u'text']
        msg_type = parsed_message[u'type']
        if not msg_sender or not  msg_text or not msg_type:
            raise ValueError("One of requried parameters is missing")
开发者ID:jenyayel,项目名称:hooks-client-rpi,代码行数:86,代码来源:client.py

示例6: ServiceBusService

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
import os
from azure.servicebus import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME
from firebase import firebase
import json

ns_key = os.environ.get('NS_KEY')
firebase = firebase.FirebaseApplication('https://logbasedev.firebaseio.com/', None)

bus_service = ServiceBusService(
    service_namespace='onroad-ns',
    shared_access_key_name='RootManageSharedAccessKey',
    shared_access_key_value=ns_key)

while True:
    msg = bus_service.receive_subscription_message('onroad-topic', 'locations', peek_lock=False)
    if msg.body:
	    for event in json.loads(msg.body):
	        new_location = {'latitude':event['lat'], 'longitude':event['long'], 'locationtime':event['time']};
	        #TODO: Remove device hardcoding
	        firebase.patch('/account/simplelogin:2/livecars/0', new_location)
开发者ID:cyberabis,项目名称:onroad-streampy,代码行数:22,代码来源:locations-consumer.py

示例7: ServiceBusService

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_subscription_message [as 别名]
arduino_password = config.get("Arduino", "Password")

pwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwd_mgr.add_password("arduino", "http://localhost/mailbox/", arduino_username, arduino_password)
handler = urllib2.HTTPBasicAuthHandler(pwd_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

try:
    sbs = ServiceBusService(namespace, shared_access_key_name=key_name, shared_access_key_value=key_value)

    sbs.create_subscription("commands", "arduino")

    while True:
        try:
            msg = sbs.receive_subscription_message("commands", "arduino")

            if msg.body:

                displayType = msg.custom_properties["messagetype"]

                logger.info("Received " + displayType + ": " + msg.body)

                url = "http://localhost/mailbox/" + msg.body

                logger.debug("Mailbox message: " + str(url))

                urllib2.urlopen(url)

                msg.delete()
        except Exception as e:
开发者ID:photomoose,项目名称:xmas-leds,代码行数:33,代码来源:durrylights.py


注:本文中的azure.servicebus.ServiceBusService.receive_subscription_message方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。