Skip to content

Instantly share code, notes, and snippets.

@immanuelpotter
Created May 28, 2020 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save immanuelpotter/ffbb0eadf20fe0e86f49acd213dbabbd to your computer and use it in GitHub Desktop.
Save immanuelpotter/ffbb0eadf20fe0e86f49acd213dbabbd to your computer and use it in GitHub Desktop.
Sending & receiving messages from Azure ServiceBus.
#!/usr/bin/env python
from azure.servicebus import QueueClient, Message
import sys, os
def main():
if 'SERVICEBUS_CONN_STRING' in os.environ:
connection_string = os.getenv("SERVICEBUS_CONN_STRING")
else:
print("Please provide connection string as envvar: SERVICEBUS_CONN_STRING")
sys.exit(3)
if 'SB_QUEUE_NAME' in os.environ:
queue_name = os.getenv("SB_QUEUE_NAME")
else:
print("Please provide queue name as envvar: SB_QUEUE_NAME")
sys.exit(4)
# Create the QueueClient
try:
queue_client = QueueClient.from_connection_string(connection_string, queue_name)
except Exception as e:
print("Could not make QueueClient from this connection string & queuename combination.")
print(e)
sys.exit(5)
# Receive the message from the queue
with queue_client.get_receiver() as queue_receiver:
messages = queue_receiver.fetch_next(timeout=3)
for message in messages:
print(message)
message.complete()
if __name__ == '__main__':
main()
#!/usr/bin/env python
from azure.servicebus import QueueClient, Message
import sys, os, json
def main():
if 'SERVICEBUS_CONN_STRING' in os.environ:
connection_string = os.getenv("SERVICEBUS_CONN_STRING")
else:
print("Please provide connection string as envvar SERVICEBUS_CONN_STRING")
sys.exit(3)
if 'SB_QUEUE_NAME' in os.environ:
queue_name = os.getenv("SB_QUEUE_NAME")
else:
print("Please provide queuename as envvar QUEUE_NAME")
sys.exit(4)
# Create the QueueClient
queue_client = QueueClient.from_connection_string(connection_string, queue_name)
json_string = """
{
"data": "lots of data"
}
"""
data = json.loads(json_string)
# Send a test message to the queue
msg = Message(json_string)
try:
queue_client.send(msg)
except Exception as e:
print("Couldn't send message! Does your queue exist?")
print(e)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment