Skip to content

Instantly share code, notes, and snippets.

@chhantyal
Last active November 17, 2017 12:34
Show Gist options
  • Save chhantyal/6043f99f9e9b54928093b36f89e10765 to your computer and use it in GitHub Desktop.
Save chhantyal/6043f99f9e9b54928093b36f89e10765 to your computer and use it in GitHub Desktop.
Python AMQP client to send messages to Azure EventHub (see line 2 & 3 to run it)
from __future__ import print_function, unicode_literals
"""
To run this script (works on both Python 2 & 3), follow these steps:
1. pip install python-qpid-proton
2. python amqp_client.py
"""
import optparse
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container
class Send(MessagingHandler):
def __init__(self, url, messages):
super(Send, self).__init__()
self.url = url
self.sent = 0
self.confirmed = 0
self.total = messages
def on_start(self, event):
event.container.create_sender(self.url)
def on_sendable(self, event):
while event.sender.credit and self.sent < self.total:
msg = Message(id=(self.sent+1), body={'sequence':(self.sent+1)})
event.sender.send(msg)
self.sent += 1
def on_accepted(self, event):
self.confirmed += 1
if self.confirmed == self.total:
print("all messages confirmed")
event.connection.close()
def on_disconnected(self, event):
self.sent = self.confirmed
parser = optparse.OptionParser(usage="usage: %prog [options]",
description="Send messages to the supplied address.")
ADDRESS = "amqps://ingress:<url-encoded-key>@vi-dev-nasp-loadgen.servicebus.windows.net:5671/vi-dev-ehub-loadgen"
parser.add_option("-a", "--address", default=ADDRESS,
help="address to which messages are sent (default %default)")
parser.add_option("-m", "--messages", type="int", default=100,
help="number of messages to send (default %default)")
opts, args = parser.parse_args()
try:
Container(Send(opts.address, opts.messages)).run()
except KeyboardInterrupt:
print("\nShutting down. Bye!")
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment