Skip to content

Instantly share code, notes, and snippets.

@brimcfadden
Created August 16, 2011 21:34
Show Gist options
  • Save brimcfadden/1150229 to your computer and use it in GitHub Desktop.
Save brimcfadden/1150229 to your computer and use it in GitHub Desktop.
Use stormed-amqp with tornado.web.RequestHandler
#!/usr/bin/env python
# tornadoweb_stormed.py
import logging
import sys
import stormed
import tornado.ioloop
import tornado.web
__author__ = 'Brian McFadden'
__email__ = 'brimcfadden@gmail.com'
HTML_HEADER = '<html><head><title>Tornado/Stormed RPC</title></head><body>'
HTML_FOOTER = '</body></html>'
class Fib(tornado.web.RequestHandler):
"""This handler implements rpc_client.py from stormed-amqp tutorial #6.
The RPC server must run simultaneously with this client. It is located at:
github.com/paolo-losi/stormed-amqp/blob/master/examples/tutorial6/rpc_server.py
Since the RPC server was not made to avoid blocking, try running several.
"""
@tornado.web.asynchronous
def get(self, number=''):
if not number:
self.redirect('/30') # GET / --> GET /30
self.number = number
mq_conn = self.application.settings.get('mq_conn')
self.mq_ch = mq_conn.channel() # One channel per request.
self.mq_ch.queue_declare(exclusive=True,
callback=self._on_q_declare)
# Go back to the IOLoop.
def _on_q_declare(self, qinfo):
# Callback function given to IOLoop.
self.mq_ch.consume(qinfo.queue, self._on_mq_response)
self.corr_id = corr_id = str(id(self))
msg = stormed.Message(str(self.number), delivery_mode=2,
reply_to=qinfo.queue, correlation_id=corr_id)
self.mq_ch.publish(msg, exchange='', routing_key='rpc_queue')
# Go back to the IOLoop.
def _on_mq_response(self, response_msg):
# Second callback function given to IOLoop.
self.write(HTML_HEADER)
self.write("fib({0}) = {1}".format(self.number, response_msg.body))
print ' [x] Received "{0}"'.format(response_msg.body)
self.write(HTML_FOOTER)
self.finish()
def main():
logging.basicConfig(level=logging.DEBUG)
# The server will use one connection per Tornado server, but one channel
# per request. If one channel per request is desired, create the channel
# after mq_conn below.
mq_conn = stormed.Connection(host='localhost')
def on_connect():
print 'Connected to AMQP broker.'
mq_conn.connect(on_connect)
application = tornado.web.Application(
[(r'/([0-9]*)', Fib)],
**{'mq_conn': mq_conn}
)
try:
port = int(sys.argv[1]) # $ python tornadoweb_stormed.py 80
except:
port = 8080
application.listen(port)
print "Tornado is serving on port {0}.".format(port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment