File: twisted_example.rst

package info (click to toggle)
python-pika 0.9.14-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,048 kB
  • ctags: 2,110
  • sloc: python: 10,046; makefile: 134
file content (49 lines) | stat: -rw-r--r-- 1,471 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Twisted Consumer Example
========================
Example of writing a consumer using the :py:class:`Twisted connection adapter <pika.adapters.twisted_connection.TwistedConnection>`::

    # -*- coding:utf-8 -*-

    import pika
    from pika import exceptions
    from pika.adapters import twisted_connection
    from twisted.internet import defer, reactor, protocol,task


    @defer.inlineCallbacks
    def run(connection):

        channel = yield connection.channel()

        exchange = yield channel.exchange_declare(exchange='topic_link',type='topic')

        queue = yield channel.queue_declare(queue='hello', auto_delete=False, exclusive=False)

        yield channel.queue_bind(exchange='topic_link',queue='hello',routing_key='hello.world')

        yield channel.basic_qos(prefetch_count=1)

        queue_object, consumer_tag = yield channel.basic_consume(queue='hello',no_ack=False)

        l = task.LoopingCall(read, queue_object)

        l.start(0.01)


    @defer.inlineCallbacks
    def read(queue_object):

        ch,method,properties,body = yield queue_object.get()

        if body:
            print body

        yield ch.basic_ack(delivery_tag=method.delivery_tag)


    parameters = pika.ConnectionParameters()
    cc = protocol.ClientCreator(reactor, twisted_connection.TwistedProtocolConnection, parameters)
    d = cc.connectTCP('hostname', 5672)
    d.addCallback(lambda protocol: protocol.ready)
    d.addCallback(run)
    reactor.run()