本文整理汇总了Python中azure.servicebus.ServiceBusService.send_queue_message方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceBusService.send_queue_message方法的具体用法?Python ServiceBusService.send_queue_message怎么用?Python ServiceBusService.send_queue_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类azure.servicebus.ServiceBusService
的用法示例。
在下文中一共展示了ServiceBusService.send_queue_message方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AzureConnection
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_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)
示例2: AzureServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_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))
示例3: ServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_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
示例4: AzureServiceBusQueue
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_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)
示例5: ServiceBusTest
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_queue_message [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):
#.........这里部分代码省略.........
示例6: ServiceBusService
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_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))
示例7: EchoLayer
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_queue_message [as 别名]
class EchoLayer(YowInterfaceLayer):
def __init__(self):
super(EchoLayer, self).__init__()
YowInterfaceLayer.__init__(self)
self.connected = False
self.serve = Serve()
self.bus_service = ServiceBusService(
service_namespace='msgtestsb',
shared_access_key_name='RootManageSharedAccessKey',
shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
@ProtocolEntityCallback("message")
def onMessage(self, recdMsg):
jsondict = {'medium': 'whatsapp'}
jsondict['phonenum'] = recdMsg.getFrom(False)
jsondict['msgtype'] = recdMsg.getType()
if jsondict['msgtype'] == 'text':
jsondict['msgbody'] = recdMsg.getBody()
if jsondict['msgtype'] == 'media':
jsondict['mediatype'] = recdMsg.getMediaType()
if jsondict['mediatype'] in ["image", "audio", "video"]:
jsondict['mediaurl'] = recdMsg.getMediaUrl()
if jsondict['mediatype'] in ["image", "video"]:
jsondict['caption'] = recdMsg.getCaption()
else:
jsondict['caption'] = None
elif jsondict['mediatype'] == 'vcard':
jsondict['name'] = recdMsg.getName()
jsondict['carddata'] = recdMsg.getCardData()
elif jsondict['mediatype'] == "location":
jsondict['lat'] = recdMsg.getLatitude()
jsondict['long'] = recdMsg.getLongitude()
jsondict['name'] = recdMsg.getLocationName()
jsondict['url'] = recdMsg.getLocationURL()
jsondict['encoding'] = "raw"
if jsondict['msgtype'] == 'text':
logging.info( recdMsg.getBody())
pushjson = json.dumps(jsondict)
if AZURE_SERVICING:
msg = Message(pushjson)
self.bus_service.send_queue_message('process_incoming', msg)
else:
retjson = self.serve.getResponseWrapper(pushjson, recdMsg)
if retjson:
SendQueue.put(retjson)
self.toLower(recdMsg.ack())
self.toLower(recdMsg.ack(True))
self.sendMessages()
def sendMessages(self):
try:
sendmsg = SendQueue.get_nowait()
except:
return
jsondict = json.loads(sendmsg)
phonenum = jsondict['phonenum']
if jsondict['restype'] == 'list':
ret = jsondict['response']
else:
ret = [(jsondict['restype'], jsondict['response'])]
for (restype,response) in ret:
logging.info( '%s: Send to %s %s ' % (datetime.now(), phonenum, restype))
if restype in [ 'image' , 'audio', 'video' ]:
if 'localfile' in response.keys():
path = response['localfile']
else:
mediaurl = response['mediaurl']
path = '/tmp/' + basename(mediaurl)
if isfile(path):
unlink(path)
urlretrieve(mediaurl, path)
if isfile(path):
if restype == 'image':
self.image_send(phonenum, path, response['caption'])
if restype == 'video':
# self.video_send(phonenum, path, response['caption'])
# video not supported yet
self.message_send(phonenum, "Video Message not supported yet")
if restype == 'audio':
# self.audio_send(phonenum, path)
# video not supported yet
self.message_send(phonenum, "Audio Message not supported yet")
elif restype == 'text':
#.........这里部分代码省略.........
示例8: ServiceBusService
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_queue_message [as 别名]
from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
service_namespace='maxqueue-ns',
shared_access_key_name='MAXRULE1',
shared_access_key_value='UBJelXoKJFsfTRnTA3c9jGWW6JXnp5Tc78cOZzdb0fI=')
msg = Message(b'Test Message')
bus_service.send_queue_message('MAXQUEUE', msg)
msg = bus_service.receive_queue_message('MAXQUEUE', peek_lock=False)
print(msg.body)
示例9: ServiceBusService
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_queue_message [as 别名]
from azure.servicebus import ServiceBusService, Message, Queue
bus_service = ServiceBusService(
service_namespace='appcandy-ns',
shared_access_key_name='MachineSend',
shared_access_key_value='Q4uctgrpqj+SZOejERPkkH0Mw0r4W4mOSb7yHSmLLI4=')
msg = Message(b'New Test Message')
bus_service.send_queue_message('appcandy', msg)
示例10: doSomething
# 需要导入模块: from azure.servicebus import ServiceBusService [as 别名]
# 或者: from azure.servicebus.ServiceBusService import send_queue_message [as 别名]
def doSomething():
# Write to log file and update Slack
hostname = socket.gethostname()
logMessage = "SIMULATOR (" + hostname + "): Creating statistics starting @ " + str(time.ctime())
log = Log()
log.info(logMessage)
notify.info(logMessage)
# Gather environment variables
AZURE_SB_SERVICE_NAMESPACE = os.getenv('AZURE_SB_SERVICE_NAMESPACE')
AZURE_SB_SHARED_ACCESS_KEY_NAME = os.getenv('AZURE_SB_SHARED_ACCESS_KEY_NAME')
AZURE_SB_SHARED_ACCESS_KEY = os.getenv('AZURE_SB_SHARED_ACCESS_KEY')
# Start loop and write random messages to Azure Service Bus Queue
x=0
while True:
x=x+1
time.sleep(2)
# Write message to SB Queue
sb_service = ServiceBusService(service_namespace=AZURE_SB_SERVICE_NAMESPACE,shared_access_key_name=AZURE_SB_SHARED_ACCESS_KEY_NAME,shared_access_key_value=AZURE_SB_SHARED_ACCESS_KEY)
msg_text = "Update number: " + str(x)
msg = Message(msg_text.encode("utf-8"))
# Randomly create data for SB Queue
r = random.randint(1, 10)
if r == 1:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'40.8','pressure':'61.93','humidity':'20','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 2:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'50.8','pressure':'62.83','humidity':'30','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 3:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'60.8','pressure':'63.73','humidity':'40','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 4:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'70.8','pressure':'64.63','humidity':'50','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 5:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'80.8','pressure':'51.93','humidity':'60','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 6:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'90.8','pressure':'55.93','humidity':'70','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 7:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'45.2','pressure':'34.99','humidity':'45','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 8:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'55.2','pressure':'38.99','humidity':'55','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
elif r == 9:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'65.2','pressure':'36.99','humidity':'65','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
else:
msg.custom_properties={'deviceid':'mydevice' + str(r),'temp':'75.2','pressure':'71.77','humidity':'38','windspeed':str(r) + '.5'}
sb_service.send_queue_message('statistics', msg)
log.info("Message #" + str(x) + " posted.")