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


Python ServiceBusService.create_queue方法代码示例

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


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

示例1: azure_service_bus_listener

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
class azure_service_bus_listener(object):
	
    def __init__(self, azure_settings):
        self.bus_service = ServiceBusService(
            service_namespace= azure_settings['name_space'],
            shared_access_key_name = azure_settings['key_name'],
            shared_access_key_value = azure_settings['key_value'])
		
        self.queue_name = azure_settings['queue_name']
	
    def wait_for_message(self, on_receive_target, on_timeout_target):
		# just in case it isn't there
        self.create_queue()
		
        message = self.bus_service.receive_queue_message(self.queue_name, peek_lock=False)
        
        if (message.body == None):
            print("[ASB_Listener]: No Message Received")
            on_timeout_target()
        else:
            message_string = message.body.decode('utf-8')
            on_receive_target(message_string)
		
    def create_queue(self):
        q_opt = Queue()
        q_opt.max_size_in_megabytes = '1024'
        q_opt.default_message_time_to_live = 'PT1M'
        self.bus_service.create_queue(self.queue_name, q_opt)
开发者ID:rumdood,项目名称:martinique,代码行数:30,代码来源:azure_service_bus_listener.py

示例2: test_two_identities

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
    def test_two_identities(self):
        # In order to run this test, 2 service bus service identities are created using
        # the sbaztool available at:
        # http://code.msdn.microsoft.com/windowsazure/Authorization-SBAzTool-6fd76d93
        #
        # Use the following commands to create 2 identities and grant access rights.
        # Replace <servicebusnamespace> with the namespace specified in the test .json file
        # Replace <servicebuskey> with the key specified in the test .json file
        # This only needs to be executed once, after the service bus namespace is created.
        #
        # sbaztool makeid user1 NoHEoD6snlvlhZm7yek9Etxca3l0CYjfc19ICIJZoUg= -n <servicebusnamespace> -k <servicebuskey>
        # sbaztool grant Send /path1 user1 -n <servicebusnamespace> -k <servicebuskey>
        # sbaztool grant Listen /path1 user1 -n <servicebusnamespace> -k <servicebuskey>
        # sbaztool grant Manage /path1 user1 -n <servicebusnamespace> -k <servicebuskey>

        # sbaztool makeid user2 Tb6K5qEgstyRBwp86JEjUezKj/a+fnkLFnibfgvxvdg= -n <servicebusnamespace> -k <servicebuskey> 
        # sbaztool grant Send /path2 user2 -n <servicebusnamespace> -k <servicebuskey>
        # sbaztool grant Listen /path2 user2 -n <servicebusnamespace> -k <servicebuskey>
        # sbaztool grant Manage /path2 user2 -n <servicebusnamespace> -k <servicebuskey>

        sbs1 = ServiceBusService(credentials.getServiceBusNamespace(), 
                                 'NoHEoD6snlvlhZm7yek9Etxca3l0CYjfc19ICIJZoUg=', 
                                 'user1')
        sbs2 = ServiceBusService(credentials.getServiceBusNamespace(), 
                                 'Tb6K5qEgstyRBwp86JEjUezKj/a+fnkLFnibfgvxvdg=', 
                                 'user2')

        queue1_name = 'path1/queue' + str(random.randint(1, 10000000))
        queue2_name = 'path2/queue' + str(random.randint(1, 10000000))

        try:
            # Create queues, success
            sbs1.create_queue(queue1_name)
            sbs2.create_queue(queue2_name)

            # Receive messages, success
            msg = sbs1.receive_queue_message(queue1_name, True, 1)
            self.assertIsNone(msg.body)
            msg = sbs1.receive_queue_message(queue1_name, True, 1)
            self.assertIsNone(msg.body)
            msg = sbs2.receive_queue_message(queue2_name, True, 1)
            self.assertIsNone(msg.body)
            msg = sbs2.receive_queue_message(queue2_name, True, 1)
            self.assertIsNone(msg.body)

            # Receive messages, failure
            with self.assertRaises(HTTPError):
                msg = sbs1.receive_queue_message(queue2_name, True, 1)
            with self.assertRaises(HTTPError):
                msg = sbs2.receive_queue_message(queue1_name, True, 1)
        finally:
            try:
                sbs1.delete_queue(queue1_name)
            except: pass
            try:
                sbs2.delete_queue(queue2_name)
            except: pass
开发者ID:Bunkerbewohner,项目名称:azure-sdk-for-python,代码行数:59,代码来源:test_servicebusservice.py

示例3: _ensureServiceBusQueuesExist

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
 def _ensureServiceBusQueuesExist(self):
     """
     Creates Azure service bus queues required by the service.
     """
     logger.info("Checking for existence of Service Bus Queues.")
     namespace = self.sbms.get_namespace(self.config.getServiceBusNamespace())
     sbs = ServiceBusService(namespace.name, namespace.default_key, issuer='owner')
     queue_names = ['jobresponsequeue', 'windowscomputequeue', 'linuxcomputequeue']
     for name in queue_names:
         logger.info("Checking for existence of Queue %s.", name)
         sbs.create_queue(name, fail_on_exist=False)
         logger.info("Queue %s is ready.", name)
开发者ID:prags,项目名称:codalab,代码行数:14,代码来源:__init__.py

示例4: main

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
def main(argv):
   print '##################################################################'
   print '#           Test Azure Service bus queue connection              #'
   print '##################################################################'

   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'

   print 'Start Parameters:'
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=False)
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Actuator queue: ' + queue_name + ' (Created)'	   
	   
   # List to hold all commands that was send no ACK received
   localCommandSendAckWaitList = []
   while True:
      cloudCommand = bus_service.receive_queue_message(queue_name, peek_lock=False)

      if cloudCommand.body is not None:
          stringCommand = str(cloudCommand.body)
          print 'C: Received "' + stringCommand + '" => ',

          #Tranlate External/Cloud ID to local network ID 
          temp = stringCommand.split("-")
          #print 'stringCommand.split = ', temp
          localNetworkDeviceID = config_data["Devices"].keys()[config_data["Devices"].values().index(temp[0])]
          print 'for DeviceId=' + localNetworkDeviceID

      time.sleep(10)
开发者ID:vicy07,项目名称:IoT_At_Home,代码行数:50,代码来源:test_azure_queue.py

示例5: azure_service_bus_listener

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
class azure_service_bus_listener(object):
	
	def __init__(self, azure_settings):
		self.bus_service = ServiceBusService(
			service_namespace= azure_settings.name_space,
			shared_access_key_name = azure_settings.key_name,
			shared_access_key_value = azure_settings.key_value)
		
		self.queue_name = azure_settings(queue_name)
	
	def wait_for_message(self, on_receive_target):
		message = self.bus_service.receive_queue_message(self.queue_name, peek_lock=False)
		message_string = message.body.decode('utf-8')
		on_receive_target(message_string)
		
	def create_queue(self):
		q_opt = Queue()
		q_opt.max_size_in_megabytes = '1024'
		q_opt.default_message_time_to_live = 'PT1M'
		self.bus_service.create_queue(self.queue_name, q_opt)
开发者ID:rumdood,项目名称:PiPython,代码行数:22,代码来源:azure_service_bus_listener.py

示例6: AzureConnection

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
class AzureConnection():
    def __init__(self):
        self.bus_service = ServiceBusService(
            service_namespace='msgtestsb',
            shared_access_key_name='RootManageSharedAccessKey',
            shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT96H'

        self.bus_service.create_queue('process_incoming', queue_options)
        self.bus_service.create_queue('whatsapp_sender', queue_options)
        self.bus_service.create_queue('myapp_sender', queue_options)
 

    def receive(self):
        msg = self.bus_service.receive_queue_message('process_incoming', peek_lock=False)
        
        if msg != None and msg.body:
                logger.info(  msg.body)
                return json.loads(msg.body)
        else:
                return None

    def send(self, jsondict):
        t = json.dumps(jsondict)
        msg = Message(t)
        logger.info(  t)
        Q = jsondict['medium'] + '_sender'
            
        self.bus_service.send_queue_message(Q, msg)
开发者ID:prasenmsft,项目名称:whatsapp,代码行数:33,代码来源:serve_azure.py

示例7: ServiceBusQueue

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
class ServiceBusQueue(object):
    def __init__(self, namespace, access_key_name, access_key_value, q_name, q_max_size="5120", msg_ttl="PT1M"):
        self.bus_svc = ServiceBusService(
            service_namespace=namespace,
            shared_access_key_name=access_key_name,
            shared_access_key_value=access_key_value,
        )
        self.queue_options = Queue()
        self.queue_options.max_size_in_megabytes = q_max_size
        self.queue_options.default_message_time_to_live = msg_ttl

        self.queue_name = q_name
        self.bus_svc.create_queue(self.queue_name, self.queue_options)

    def send(self, msg):
        message = bytes(msg)
        message = Message(message)
        self.bus_svc.send_queue_message(self.queue_name, message)

    def receive(self):
        msg = self.bus_svc.receive_queue_message(self.queue_name, peek_lock=False)
        data = ast.literal_eval(msg.body)
        return data
开发者ID:NerdCats,项目名称:ShadowCat,代码行数:25,代码来源:servicebus_queue.py

示例8: watchAzureQueue

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
def watchAzureQueue():
        global Counter
        if AZURE_RECEIVING == False:
            return 

        bus_service = ServiceBusService(
            service_namespace='msgtestsb',
            shared_access_key_name='RootManageSharedAccessKey',
            shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT96H'

        bus_service.create_queue('process_incoming', queue_options)
        bus_service.create_queue('whatsapp_sender', queue_options)
 
        while not isfile('/home/bitnami1/whatsapp/.stopwhatsapp') and Counter > 1:
            msg = bus_service.receive_queue_message('whatsapp_sender', peek_lock=False)
            if msg != None and msg.body:
                logging.info( '%s ' % datetime.now() +  msg.body)
                SendQueue.put(msg.body)
            else:
                logging.info( '%s ' % datetime.now() +  "Empty Azure Queue")
    	        time.sleep(4.6)
开发者ID:prasenmsft,项目名称:whatsapp,代码行数:26,代码来源:run.py

示例9: ServiceBusTest

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
class ServiceBusTest(AzureTestCase):

    def setUp(self):
        self.sbs = ServiceBusService(credentials.getServiceBusNamespace(),
                                     credentials.getServiceBusKey(),
                                     'owner')

        self.sbs.set_proxy(credentials.getProxyHost(),
                           credentials.getProxyPort(),
                           credentials.getProxyUser(),
                           credentials.getProxyPassword())

        __uid = getUniqueTestRunID()

        queue_base_name = u'mytestqueue%s' % (__uid)
        topic_base_name = u'mytesttopic%s' % (__uid)

        self.queue_name = getUniqueNameBasedOnCurrentTime(queue_base_name)
        self.topic_name = getUniqueNameBasedOnCurrentTime(topic_base_name)

        self.additional_queue_names = []
        self.additional_topic_names = []

    def tearDown(self):
        self.cleanup()
        return super(ServiceBusTest, self).tearDown()

    def cleanup(self):
        try:
            self.sbs.delete_queue(self.queue_name)
        except:
            pass

        for name in self.additional_queue_names:
            try:
                self.sbs.delete_queue(name)
            except:
                pass

        try:
            self.sbs.delete_topic(self.topic_name)
        except:
            pass

        for name in self.additional_topic_names:
            try:
                self.sbs.delete_topic(name)
            except:
                pass

    #--Helpers-----------------------------------------------------------------
    def _create_queue(self, queue_name):
        self.sbs.create_queue(queue_name, None, True)

    def _create_queue_and_send_msg(self, queue_name, msg):
        self._create_queue(queue_name)
        self.sbs.send_queue_message(queue_name, msg)

    def _create_topic(self, topic_name):
        self.sbs.create_topic(topic_name, None, True)

    def _create_topic_and_subscription(self, topic_name, subscription_name):
        self._create_topic(topic_name)
        self._create_subscription(topic_name, subscription_name)

    def _create_subscription(self, topic_name, subscription_name):
        self.sbs.create_subscription(topic_name, subscription_name, None, True)

    #--Test cases for service bus service -------------------------------------
    def test_create_service_bus_missing_arguments(self):
        # Arrange
        if os.environ.has_key(AZURE_SERVICEBUS_NAMESPACE):
            del os.environ[AZURE_SERVICEBUS_NAMESPACE]
        if os.environ.has_key(AZURE_SERVICEBUS_ACCESS_KEY):
            del os.environ[AZURE_SERVICEBUS_ACCESS_KEY]
        if os.environ.has_key(AZURE_SERVICEBUS_ISSUER):
            del os.environ[AZURE_SERVICEBUS_ISSUER]

        # Act
        with self.assertRaises(WindowsAzureError):
            sbs = ServiceBusService()

        # Assert

    def test_create_service_bus_env_variables(self):
        # Arrange
        os.environ[
            AZURE_SERVICEBUS_NAMESPACE] = credentials.getServiceBusNamespace()
        os.environ[
            AZURE_SERVICEBUS_ACCESS_KEY] = credentials.getServiceBusKey()
        os.environ[AZURE_SERVICEBUS_ISSUER] = 'owner'

        # Act
        sbs = ServiceBusService()

        if os.environ.has_key(AZURE_SERVICEBUS_NAMESPACE):
            del os.environ[AZURE_SERVICEBUS_NAMESPACE]
        if os.environ.has_key(AZURE_SERVICEBUS_ACCESS_KEY):
            del os.environ[AZURE_SERVICEBUS_ACCESS_KEY]
        if os.environ.has_key(AZURE_SERVICEBUS_ISSUER):
#.........这里部分代码省略.........
开发者ID:slick666,项目名称:azure-sdk-for-python,代码行数:103,代码来源:test_servicebusservice.py

示例10: main

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
def main(argv):
   print '##################################################################'
   print '#                         NRF24 gateway                          #'
   print '##################################################################'


   # Wait while internet appear
   import urllib2 
   loop_value = 1
   while (loop_value < 10):
      try:
           urllib2.urlopen("http://google.com")
      except:
           print( "Network: currently down." )
           time.sleep( 10 )
           loop_value = loop_value + 1
      else:
           print( "Network: Up and running." )
           loop_value = 10


   pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xd2], [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]]
   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
   debugMode = 0

   try:
      opts, args = getopt.getopt(argv,"hd:f:",["debug=","configFile="])
   except getopt.GetoptError:
      print 'smart_gateway.py -d <debugMode:0/1>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'Example for call it in debug mode: smart_gateway.py -d 1 -f config.json'
         sys.exit()
      elif opt in ("-d", "--debug"):
         debugMode = arg
      elif opt in ("-f", "--configFile"):
         configFileName = arg

   print 'Start Parameters:'
   print '       debugMode:', debugMode
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Server URL:', config_data["Server"]["url"]
   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   print ''
   nowPI = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

   href = config_data["Server"]["url"] + 'API/Device/GetServerDateTime'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ':' + token
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Authentication': authentication}
   #r = requests.get(href, headers=headers, verify=False)
   r = requests.get(href, headers=headers)
   if r.status_code == 200:
       nowPI = r.json()
       print ("Setting up time to: " + nowPI)
       os.popen('sudo -S date -s "' + nowPI + '"', 'w').write("123")
   else:
       print 'Error in setting time. Server response code: %i' % r.status_code

   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=False)
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Actuator queue: ' + queue_name + ' (Created)'	   
	   
   href = config_data["Server"]["url"] + 'api/Device/DeviceConfigurationUpdate'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ":" + token


   if debugMode==1: print(authentication)
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Timestamp': nowPI, 'Authentication': authentication}
    
   deviceDetail = {}
   deviceDetail["DeviceIdentifier"] = config_data["Server"]["Deviceid"]
   deviceDetail["DeviceType"] = "Custom"
   deviceDetail["DeviceConfigurations"] = [{'Key':'IPPrivate','Value':[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]},
                                           {'Key':'IPPublic','Value': requests.get('http://icanhazip.com/').text},
                                           {'Key': 'Configuration', 'Value': json.dumps(config_data) },
                                           {'Key':'MAC','Value': ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2))}
                                          ]

   payload = {'Device': deviceDetail}
#.........这里部分代码省略.........
开发者ID:vicy07,项目名称:IoT_At_Home,代码行数:103,代码来源:smart_gateway.py

示例11: ServiceBusService

# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import create_queue [as 别名]
import azurecfg
from azure.servicebus import ServiceBusService, Message, Queue

bus_service = ServiceBusService(
        service_namespace='atdblasphemy',
        shared_access_key_name=azurecfg.servicebus['name'],
        shared_access_key_value=azurecfg.servicebus['key'])

bus_service.create_queue('atd')
开发者ID:nikolaplejic,项目名称:atdazure.py,代码行数:11,代码来源:azurequeue.py


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