Created
November 3, 2010 21:24
-
-
Save brimcfadden/661743 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import tornado.httpserver | |
import tornado.ioloop | |
import tornado.web | |
import multiprocessing | |
import random | |
import time | |
__author__ = 'Brian McFadden' | |
__email__ = '[email protected]' | |
class AsyncHandler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(self): | |
print "New request: entering AsyncHandler.get" | |
# Creating a pipe returns two file descriptors (one for each end). | |
fd1, fd2 = multiprocessing.Pipe() | |
self.pipe = fd1 | |
fno = fd1.fileno() | |
# Create a process for the sleepy function. Provide one pipe end. | |
p = multiprocessing.Process(target=sleepy, args=(fd2,)) | |
p.start() | |
iol = tornado.ioloop.IOLoop.instance() | |
iol.add_handler(fno, self.async_callback(self._finish), iol.READ) | |
print "Leaving AsyncHandler.get." | |
def _finish(self, fd, event): | |
print "Entering AsyncHandler._finish" | |
tornado.ioloop.IOLoop.instance().remove_handler(fd) | |
val = self.pipe.recv() | |
self.pipe.close() | |
self.write(val) | |
self.write(random_num()) | |
print "Finishing the request." | |
self.finish() | |
class MainHandler(tornado.web.RequestHandler): | |
def get(self): | |
print "New request: entering MainHandler.get" | |
self.write(random_num()) | |
print "Finishing the request." | |
def random_num(): | |
n = random.random() | |
return "Here is a random number to show change: {0}".format(n) | |
def sleepy(pipe): | |
time.sleep(5) | |
pipe.send("Now I'm awake.") | |
pipe.close() | |
return | |
if __name__ == '__main__': | |
application = tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/async", AsyncHandler), | |
]) | |
http_server = tornado.httpserver.HTTPServer(application) | |
http_server.listen(8888) | |
print 'The HTTP server is listening on port 8888.' | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment