Debian Codegraph @

python/examples/db_recv.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.handlers import MessagingHandler
23 from proton.reactor import ApplicationEvent, Container, EventInjector
24 from db_common import Db
25
26
27 class Recv(MessagingHandler):
28 def __init__(self, url, count):
29 super(Recv, self).__init__(auto_accept=False)
30 self.url = url
31 self.delay = 0
32 self.last_id = None
33 self.expected = count
34 self.received = 0
35 self.accepted = 0
36 self.db = Db("dst_db", EventInjector())
37
38 def on_start(self, event):
39 event.container.selectable(self.db.injector)
40 e = ApplicationEvent("id_loaded")
41 e.container = event.container
42 self.db.get_id(e)
43
44 def on_id_loaded(self, event):
45 self.last_id = event.id
46 event.container.create_receiver(self.url)
47
48 def on_record_inserted(self, event):
49 self.accept(event.delivery)
50 self.accepted += 1
51 if self.accepted == self.expected:
52 event.connection.close()
53 self.db.close()
54
55 def on_message(self, event):
56 id = int(event.message.id)
57 if (not self.last_id) or id > self.last_id:
58 if self.expected == 0 or self.received < self.expected:
59 self.received += 1
60 self.last_id = id
61 self.db.insert(id, event.message.body, ApplicationEvent("record_inserted", delivery=event.delivery))
62 print("inserted message %s" % id)
63 else:
64 self.release(event.delivery)
65 else:
66 self.accept(event.delivery)
67
68
69 parser = optparse.OptionParser(usage="usage: %prog [options]")
70 parser.add_option("-a", "--address", default="localhost:5672/examples",
71 help="address from which messages are received (default %default)")
72 parser.add_option("-m", "--messages", type="int", default=0,
73 help="number of messages to receive; 0 receives indefinitely (default %default)")
74 opts, args = parser.parse_args()
75
76 try:
77 Container(Recv(opts.address, opts.messages)).run()
78 except KeyboardInterrupt:
79 pass