~ubuntu-branches/ubuntu/wily/pyzmq/wily

« back to all changes in this revision

Viewing changes to examples/eventloop/asyncweb.py

  • Committer: Package Import Robot
  • Author(s): Julian Taylor
  • Date: 2013-02-24 19:23:15 UTC
  • mfrom: (1.2.1) (9 sid)
  • mto: This revision was merged to the branch mainline in revision 10.
  • Revision ID: package-import@ubuntu.com-20130224192315-qhmwp3m3ymk8r60d
Tags: 2.2.0.1-1
* New upstream release
* relicense debian packaging to LGPL-3
* update watch file to use github directly
  thanks to Bart Martens for the file
* add autopkgtests
* drop obsolete DM-Upload-Allowed
* bump standard to 3.9.4, no changes required

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""Async web request example with tornado.
 
2
 
 
3
Requests to localhost:8888 will be relayed via 0MQ to a slow responder,
 
4
who will take 1-5 seconds to respond.  The tornado app will remain responsive
 
5
duriung this time, and when the worker replies, the web request will finish.
 
6
 
 
7
A '.' is printed every 100ms to demonstrate that the zmq request is not blocking
 
8
the event loop.
 
9
"""
 
10
 
 
11
 
 
12
import sys
 
13
import random
 
14
import threading
 
15
import time
 
16
 
 
17
import zmq
 
18
from zmq.eventloop import ioloop, zmqstream
 
19
 
 
20
"""
 
21
ioloop.install() must be called prior to instantiating *any* tornado objects,
 
22
and ideally before importing anything from tornado, just to be safe.
 
23
 
 
24
install() sets the singleton instance of tornado.ioloop.IOLoop with zmq's
 
25
IOLoop. If this is not done properly, multiple IOLoop instances may be
 
26
created, which will have the effect of some subset of handlers never being
 
27
called, because only one loop will be running.
 
28
"""
 
29
 
 
30
ioloop.install()
 
31
 
 
32
import tornado
 
33
from tornado import web
 
34
 
 
35
 
 
36
def slow_responder():
 
37
    """thread for slowly responding to replies."""
 
38
    ctx = zmq.Context.instance()
 
39
    socket = ctx.socket(zmq.REP)
 
40
    socket.linger = 0
 
41
    socket.bind('tcp://127.0.0.1:5555')
 
42
    i=0
 
43
    while True:
 
44
        msg = socket.recv()
 
45
        print "\nworker received %r\n" % msg
 
46
        time.sleep(random.randint(1,5))
 
47
        socket.send(msg + " to you too, #%i" % i)
 
48
        i+=1
 
49
 
 
50
def dot():
 
51
    """callback for showing that IOLoop is still responsive while we wait"""
 
52
    sys.stdout.write('.')
 
53
    sys.stdout.flush()
 
54
 
 
55
def printer(msg):
 
56
    print (msg)
 
57
 
 
58
class TestHandler(web.RequestHandler):
 
59
    
 
60
    @web.asynchronous
 
61
    def get(self):
 
62
        ctx = zmq.Context.instance()
 
63
        s = ctx.socket(zmq.REQ)
 
64
        s.connect('tcp://127.0.0.1:5555')
 
65
        # send request to worker
 
66
        s.send('hello')
 
67
        loop = ioloop.IOLoop.instance()
 
68
        self.stream = zmqstream.ZMQStream(s)
 
69
        self.stream.on_recv(self.handle_reply)
 
70
    
 
71
    def handle_reply(self, msg):
 
72
        # finish web request with worker's reply
 
73
        reply = msg[0]
 
74
        print "\nfinishing with %r\n" % reply,
 
75
        self.stream.close()
 
76
        self.write(reply)
 
77
        self.finish()
 
78
 
 
79
def main():
 
80
    worker = threading.Thread(target=slow_responder)
 
81
    worker.daemon=True
 
82
    worker.start()
 
83
    
 
84
    application = web.Application([(r"/", TestHandler)])
 
85
    beat = ioloop.PeriodicCallback(dot, 100)
 
86
    beat.start()
 
87
    application.listen(8888)
 
88
    try:
 
89
        ioloop.IOLoop.instance().start()
 
90
    except KeyboardInterrupt:
 
91
        print ' Interrupted'
 
92
    
 
93
    
 
94
if __name__ == "__main__":
 
95
    main()
 
96