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


Python servicebus.ServiceBusService类代码示例

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


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

示例1: SweetieMQ

class SweetieMQ(object):

    bus_service = None
    topic = None

    def __init__(self, config):
        account_key = getattr(config, 'sb_account_key', None)
        issuer = getattr(config, 'sb_issuer', None)
        if issuer is None:
            issuer = 'owner'
        if account_key is None:
            return

        self.bus_service = ServiceBusService(service_namespace='jabber-fimsquad',\
                account_key=account_key, issuer=issuer)
        self.topic = 'chat-general'

    def send(self, message):
        if self.bus_service is None:
            return
        log.debug('Sending message '+str(message))
        msg = Message(message)
        try:
            self.bus_service.send_topic_message(self.topic, msg)
        except Exception as e:
            log.error("MESSAGE DELIVERY FAILED: "+str(e))
开发者ID:gamefreak,项目名称:sweetiebot,代码行数:26,代码来源:SweetieMQ.py

示例2: main

def main():
  parser = argparse.ArgumentParser(description='Run automated diagnostics')
  parser.add_argument('-y', action='store_true', help='Skip prompts')
  parser.add_argument('--anonymous', action='store_true', help='No telemetry')
  parser.add_argument('--case', help='Link output with a case, for use with Azure Support')
  parser.add_argument('--human', action='store_true', help='Write human-readable text to stdout')
  parser.add_argument('--feedback', action='store_true', help='Provide suggestions and/or feedback')

  args=parser.parse_args()

  if(args.feedback):
    suggestion = raw_input("Suggestion (Press return to submit):  ")
    sbkey = '5QcCwDvDXEcrvJrQs/upAi+amTRMXSlGNtIztknUnAA='
    sbs = ServiceBusService('linuxdiagnostics-ns', shared_access_key_name='PublicProducer', shared_access_key_value=sbkey)
    event = {'event': 'feedback', 'feedback': suggestion}
    sbs.send_event('linuxdiagnostics',json.dumps(event))
    exit()

  if(args.anonymous):
    if(args.case == True):
      print "Cannot report case diagnostics in anonymous mode."
    else:
      Diagnostics(False,args.case).print_report(args.human)
  else:
    if(args.y):
      Diagnostics(True,args.case).print_report(args.human)
    else:
      prompt="In order to streamline support and drive continuous improvement, this script may transmit system data to Microsoft.\n Do you consent to this? (y/n):"
      consent=raw_input(prompt)
      if(consent=='y' or consent=='Y'):
        Diagnostics(True,args.case).print_report(args.human)
      else:
        print("To run without telemetry, use the --anonymous flag")
开发者ID:craiglandis,项目名称:scripts,代码行数:33,代码来源:diagnostics.py

示例3: azure_service_bus_listener

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,代码行数:28,代码来源:azure_service_bus_listener.py

示例4: __init__

class Diagnostics:
  def __init__(self,telemetry,case):
    self.sbkey = '5QcCwDvDXEcrvJrQs/upAi+amTRMXSlGNtIztknUnAA='
    self.sbs = ServiceBusService('linuxdiagnostics-ns', shared_access_key_name='PublicProducer', shared_access_key_value=self.sbkey)
    self.telemetry = telemetry
    self.case = case
    self.report = dict()
    self.data = dict()
    try:
      self.data['fstab'] = fstab()
      self.data['vmstat'] = vmstat()
      self.data['diskstats'] = diskstats()
      self.data['meminfo'] = meminfo()
      self.data['loadavg'] = loadavg()
      self.data['proc.sys.fs'] = procsysfs()
      self.data['inodes_by_mount'] = inodes_by_mp()
      self.data['waagent'] = waagent()
      self.check_fstab_uuid()
      self.check_resourcedisk_inodes()
      self.success_telemetry()
    except:
      self.error_telemetry(str(sys.last_value))
      exit()

  def print_report(self,human):
    if(human):
      for item in map(lambda x: human_readable(self.report[x]),self.report):
        print item
    else:
      print json.dumps(self.report)

# == Telemetry ==
  def success_telemetry(self):
    if(self.telemetry):
      event = {'event': 'success', 'report': self.report, 'data': self.data}
      if(self.case):
        event['case'] = self.case
      self.sbs.send_event('linuxdiagnostics',json.dumps(event))

  def error_telemetry(self,e):
    if(self.telemetry):
      event = {'event': 'error', 'error': e, 'report': self.report, 'data':self.data}
      if(self.case):
        event['case'] = self.case
      sbs.send_event('linuxdiagnostics',json.dumps(event))

# == Diagnostics ==
  def check_fstab_uuid(self):
    uuids = map (lambda r:bool(re.match('UUID',r['fs_spec'],re.I)), self.data['fstab'])
    uuids = filter(lambda x: not x, uuids)
    if(len(uuids) > 0):
      self.report['linux.uuid']= report("fstab doesn't use UUIDs", 'red', 'best_practices', "/etc/fstab isn't using UUIDs to reference its volumes.", '')

  def check_resourcedisk_inodes(self):
    mountpoint = self.data['waagent']['ResourceDisk.MountPoint']
    x=filter(lambda x: x['mountpoint']==mountpoint ,self.data['inodes_by_mount'])[0]
    if(x['inodes_used'] > 20):
      self.report['azure.resource_disk_usage'] = report('Resource Disk Usage', 'yellow', 'data_loss',"This instance appears to be using the resource disk. Data stored on this mountpoint may be lost.", '')
开发者ID:craiglandis,项目名称:scripts,代码行数:58,代码来源:diagnostics.py

示例5: send_temperature

def send_temperature(temp):
    today = datetime.datetime.now()
    now = str(today)    
    sbs = ServiceBusService(service_namespace=sb_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value)    
    print ('sending to Event [email protected]' + now)
    event_message = '{ "DeviceId": "' + device_id + '", "DeviceName": "' + device_name + '", "Temperature": "' + str(temp) + '", "TimeStamp": "' + now + '" }'
    print (event_message)
    sbs.send_event(hub_name, event_message)            
    print ('sent!')    
开发者ID:Hitchhikrr,项目名称:Hackathon-1,代码行数:9,代码来源:monitor.py

示例6: EventHubSender

class EventHubSender(BaseSender):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._sender = ServiceBusService(self._config.service_namespace,
                                         shared_access_key_name=self._config.key_name,
                                         shared_access_key_value=self._config.key_value)

    def send(self, label, data):
        assert isinstance(label, str), 'label must be a string'
        self._sender.send_event(label, data)
开发者ID:radiusinc,项目名称:Expedia-EMF-SDK,代码行数:10,代码来源:event_hub_sender.py

示例7: AzureConnection

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,代码行数:31,代码来源:serve_azure.py

示例8: AzureWorker

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,代码行数:55,代码来源:azureworker.py

示例9: workerthread

def workerthread():
    # outer loop to run while waiting
    from azure.servicebus import ServiceBusService, Message, Queue
    bus_read_service = ServiceBusService(
        service_namespace='vmsseight',
        shared_access_key_name='ListenOneTime',
        shared_access_key_value='OhFgmG5Cr/K9aOrE29YL7eXERzmUb3Fpf7J+FoBhiMw=')
    while (True):
        # main loop to thrash the CPI
        while (keepworking == True):
            msg = bus_read_service.receive_queue_message('vmsseightqueue', peek_lock=False)
        time.sleep(3)
开发者ID:irwinwilliams,项目名称:azure-quickstart-templates,代码行数:12,代码来源:workserver.py

示例10: _ensureServiceBusQueuesExist

 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,代码行数:12,代码来源:__init__.py

示例11: __init__

class azure_interface:
  def __init__(self, name_space, key_name, key_value, proxy = None):
    self.sbs = ServiceBusService(service_namespace=name_space,shared_access_key_name=key_name, shared_access_key_value=key_value)
    if proxy:
      self.sbs.set_proxy('proxy.iisc.ernet.in',3128)

  def event_send(self, hubname ,msg):
    try:
      hubStatus = self.sbs.send_event(hubname, str(msg))
      print "Send Status:", repr(hubStatus)
    except:
      print sys.exc_info()               
开发者ID:dream-lab,项目名称:iot-school,代码行数:12,代码来源:azure_handler.py

示例12: azure_autheticate

def azure_autheticate():
    key_name = 'beardcavekey' # SharedAccessKeyName from Azure portal
    key_value = 'qc4xkJJlpEiRpcwCiD56dh/oxJBlhmM0gCwUcYw10GM=' # SharedAccessKey from Azure portal
    service_namespace = 'beardcave'
    sbs = ServiceBusService(service_namespace,
                            shared_access_key_name=key_name,
                            shared_access_key_value=key_value)

    print "authenticated"
    msg = Message('g3 off')
    sbs.send_topic_message('lighttopic', msg)
    # msg = sbs.receive_subscription_message('lighttopic', 'lightsubscription', peek_lock=True)
    print(msg.body)
    print "sent"
开发者ID:dpeet,项目名称:tenforward,代码行数:14,代码来源:azuremsgoff.py

示例13: on_data

    def on_data(self, data):

        # Twitter returns data in JSON format - we need to decode it first
		decoded = json.loads(data)

        # # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
        # print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
        # print ''
        # return True

		sbs = ServiceBusService(service_namespace=config.servns, shared_access_key_name=config.key_name, shared_access_key_value=config.key_value)
		searched_tweets = "{ 'source': '" + unicode(decoded['user']['screen_name']) + "' , 'text': '" + unicode(decoded['text'].encode('ascii', 'ignore')) + "' }"
		print(unicode(searched_tweets))
		sbs.send_event('iot', unicode(searched_tweets))

		return True
开发者ID:Gyt94,项目名称:PPD1516-CloudComputing,代码行数:16,代码来源:streamingTwitter.py

示例14: __init__

	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)
开发者ID:rumdood,项目名称:PiPython,代码行数:7,代码来源:azure_service_bus_listener.py

示例15: __init__

 def __init__(self, namespace, key, issuer, shared_access_key_name, shared_access_key_value, name):
     self.service = ServiceBusService(service_namespace=namespace, account_key=key,
                                      issuer=issuer, shared_access_key_name=shared_access_key_name,
                                      shared_access_key_value=shared_access_key_value)
     self.name = name
     self.max_retries = 3
     self.wait = lambda count: 1.0*(2**count)
开发者ID:codalab,项目名称:codalab-competitions,代码行数:7,代码来源:azure_extensions.py


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