本文整理汇总了Python中azure.servicebus.ServiceBusService.receive_queue_message方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceBusService.receive_queue_message方法的具体用法?Python ServiceBusService.receive_queue_message怎么用?Python ServiceBusService.receive_queue_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类azure.servicebus.ServiceBusService
的用法示例。
在下文中一共展示了ServiceBusService.receive_queue_message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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)
示例2: azure_service_bus_listener
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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)
示例3: AzureConnection
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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)
示例4: workerthread
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
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)
示例5: test_two_identities
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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
示例6: AzureServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
class AzureServiceBusQueue(Queue):
"""
Implements a Queue backed by a Windows Azure Service Bus Queue.
"""
# Timeout in seconds. receive_message is blocking and returns as soon as one of two
# conditions occurs: a message is received or the timeout period has elapsed.
polling_timeout = 60
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)
def _try_request(self, fn, retry_count=0, fail=None):
'''Helper to retry request for sending and receiving messages.'''
try:
return fn()
except (WindowsAzureError) as e:
if retry_count < self.max_retries:
logger.error("Retrying request after error occurred. Attempt %s of %s.",
retry_count+1, self.max_retries)
wait_interval = self.wait(retry_count)
if wait_interval > 0.0:
sleep(wait_interval)
return self._try_request(fn, retry_count=retry_count+1, fail=fail)
else:
if fail is not None:
fail()
raise e
def receive_message(self):
op = lambda: self.service.receive_queue_message(self.name,
peek_lock=False,
timeout=self.polling_timeout)
msg = self._try_request(op)
return None if msg.body is None else AzureServiceBusQueueMessage(self, msg)
def send_message(self, body):
op = lambda: self.service.send_queue_message(self.name, Message(body))
fail = lambda: logger.error("Failed to send message. Message body is:\n%s", body)
self._try_request(op, fail=fail)
示例7: AzureServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
class AzureServiceBusQueue(Queue):
"""
Implements a Queue backed by a Windows Azure Service Bus Queue.
"""
# Timeout in seconds. receive_message is blocking and returns as soon as one of two
# conditions occurs: a message is received or the timeout period has elapsed.
polling_timeout = 60
def __init__(self, namespace, key, issuer, name):
self.service = ServiceBusService(service_namespace=namespace, account_key=key, issuer=issuer)
self.name = name
def receive_message(self):
msg = self.service.receive_queue_message(self.name, peek_lock=False, timeout=self.polling_timeout)
return None if msg.body is None else AzureServiceBusQueueMessage(self, msg)
def send_message(self, body):
self.service.send_queue_message(self.name, Message(body))
示例8: azure_service_bus_listener
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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)
示例9: main
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
def main(argv):
print 'Starting program...'
internalDeviceId = argv[0]
json_data=open('config.json')
config_data = json.load(json_data)
json_data.close()
externalDeviceId = config_data["Devices"][internalDeviceId]
queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"] + '_' + externalDeviceId
print (queue_name)
bus_service = ServiceBusService( service_namespace='rdciot', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value='EXeZe7r49jCoDz79fESxtMdXwYU6iQwG1Gbo8J4HXyY=')
print bus_service
while True:
msg = bus_service.receive_queue_message(queue_name, peek_lock=False)
print(msg.body)
print 'Program finished.'
示例10: ServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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
示例11: watchAzureQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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)
示例12: ServiceBusTest
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
#.........这里部分代码省略.........
# Assert
self.assertTrue(deleted)
queues = self.sbs.list_queues()
self.assertNamedItemNotInContainer(queues, self.queue_name)
def test_delete_queue_with_non_existing_queue(self):
# Arrange
# Act
deleted = self.sbs.delete_queue(self.queue_name)
# Assert
self.assertFalse(deleted)
def test_delete_queue_with_non_existing_queue_fail_not_exist(self):
# Arrange
# Act
with self.assertRaises(WindowsAzureError):
self.sbs.delete_queue(self.queue_name, True)
# Assert
def test_send_queue_message(self):
# Arrange
self._create_queue(self.queue_name)
sent_msg = Message('send message')
# Act
self.sbs.send_queue_message(self.queue_name, sent_msg)
# Assert
def test_receive_queue_message_read_delete_mode(self):
# Assert
sent_msg = Message('receive message')
self._create_queue_and_send_msg(self.queue_name, sent_msg)
# Act
received_msg = self.sbs.receive_queue_message(self.queue_name, False)
# Assert
self.assertIsNotNone(received_msg)
self.assertEquals(sent_msg.body, received_msg.body)
def test_receive_queue_message_read_delete_mode_throws_on_delete(self):
# Assert
sent_msg = Message('receive message')
self._create_queue_and_send_msg(self.queue_name, sent_msg)
# Act
received_msg = self.sbs.receive_queue_message(self.queue_name, False)
with self.assertRaises(WindowsAzureError):
received_msg.delete()
# Assert
def test_receive_queue_message_read_delete_mode_throws_on_unlock(self):
# Assert
sent_msg = Message('receive message')
self._create_queue_and_send_msg(self.queue_name, sent_msg)
# Act
received_msg = self.sbs.receive_queue_message(self.queue_name, False)
with self.assertRaises(WindowsAzureError):
received_msg.unlock()
示例13: ServiceBusService
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
from azure.servicebus import ServiceBusService
service_namespace = 'dev-montavo'
account_key = '3me4sCOHDWBK8PkjkznLnFkksQ0H/aWL3FU/JlzF5d0='
sbs = ServiceBusService(service_namespace, account_key, 'owner')
[q.name for q in sbs.list_queues()]
q = sbs.list_queues()[0]
m = sbs.receive_queue_message(q.name)
m.body
m.custom_properties
示例14: ServiceBusService
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [as 别名]
from azure.servicebus import ServiceBusService, Message, Queue
namespace = "nsgtrnamespace"
endpoint = "sb://" + namespace + ".servicebus.windows.net/"
keyName = "all"
key = "KbuVe06trwIaVPeYYg/F+WfmojIi+pdWe4SrD5BBczY="
queueName = "nsgtrqueue"
bus_service = ServiceBusService(
service_namespace=namespace,
shared_access_key_name=keyName,
shared_access_key_value=key
)
sentMsg = Message(b'hi')
bus_service.send_queue_message(queueName, sentMsg)
receivedMsg = bus_service.receive_queue_message(queueName, peek_lock=False)
print(receivedMsg.body)
#print(bus_service.receive_queue_message(queueName, peek_lock=False))
示例15: main
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import receive_queue_message [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}
#.........这里部分代码省略.........