Debian Codegraph @

python/examples/colour_send.py

raw
1 #!/usr/bin/env python3
2 #
3 # Licensed to the Apache Software Foundation (ASF) under one
4 # or more contributor license agreements. See the NOTICE file
5 # distributed with this work for additional information
6 # regarding copyright ownership. The ASF licenses this file
7 # to you under the Apache License, Version 2.0 (the
8 # "License"); you may not use this file except in compliance
9 # with the License. You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing,
14 # software distributed under the License is distributed on an
15 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 # KIND, either express or implied. See the License for the
17 # specific language governing permissions and limitations
18 # under the License.
19 #
20
21 import optparse
22 from proton import Message
23 from proton.handlers import MessagingHandler
24 from proton.reactor import Container
25
26
27 class Send(MessagingHandler):
28 def __init__(self, url, messages):
29 super(Send, self).__init__()
30 self.url = url
31 self.sent = 0
32 self.confirmed = 0
33 self.total = messages
34
35 def on_start(self, event):
36 event.container.create_sender(self.url)
37
38 def on_sendable(self, event):
39 while event.sender.credit and self.sent < self.total:
40 if self.sent % 2:
41 colour = 'red'
42 else:
43 colour = 'green'
44 content = '%s %d' % (colour, self.sent + 1)
45 msg = Message(id=(self.sent + 1), properties={'colour': colour}, body=content)
46 event.sender.send(msg)
47 self.sent += 1
48
49 def on_accepted(self, event):
50 self.confirmed += 1
51 if self.confirmed == self.total:
52 print("all messages confirmed")
53 event.connection.close()
54
55 def on_disconnected(self, event):
56 self.sent = self.confirmed
57
58
59 parser = optparse.OptionParser(usage="usage: %prog [options]",
60 description="Send messages to the supplied address.")
61 parser.add_option("-a", "--address", default="localhost:5672/examples",
62 help="address to which messages are sent (default %default)")
63 parser.add_option("-m", "--messages", type="int", default=100,
64 help="number of messages to send (default %default)")
65 opts, args = parser.parse_args()
66
67 try:
68 Container(Send(opts.address, opts.messages)).run()
69 except KeyboardInterrupt:
70 pass