Twisted API for Couchbase not working with Pornon Tornado

I am trying to start a Tornado server with Couchbase 4.0 Developer preview.

import tornado.web
import tornado.httpserver
import tornado.options
import tornado.ioloop
import tornado.websocket
import tornado.httpclient
from tornado import gen
import os.path
from tornado.options import define, options, parse_command_line
import time

#from couchbase.bucket import Bucket
from twisted.internet import reactor
from txcouchbase.bucket import Bucket

from couchbase.n1ql import N1QLQuery, N1QLError
from pprint import pprint

server = "x.x.x.x"
bucketname = "zips"

Connection = "couchbase://" + server + "/" + bucketname

bkt = Bucket(Connection)

class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous   
    def get(self):
        print "entered"
        query = "SELECT * FROM `zips` where pincode= '632014'"
        q = N1QLQuery(query)
        #self.bkt = bkt
        t0 = time.time()
        res = bkt.n1qlQueryAll(q)
        res.addCallback(self.on_ok)
        reactor.run()
        t1 = time.time()
        print t1-t0
        self.write("Hello World")

    def on_ok(self,response):
        print "LOl"
        for each in res:
            print each
        reactor.stop()
        self.finish()

handlers = [
    (r'/',IndexHandler),
]

if __name__ == "__main__":
    parse_command_line()
    # template path should be given here only unlike handlers
    app = tornado.web.Application(handlers, template_path=os.path.join(os.path.dirname(__file__), "templates"),
                                  static_path=os.path.join(os.path.dirname(__file__), "static"), cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", debug=True)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8888, address='0.0.0.0')
    tornado.ioloop.IOLoop.instance().start()

      

After I run this, for some reason the callback function is never called. I couldn't find any suitable documentation for this and I had to go through the source code to write this. I am still confused as I am new to asynchronous programming. Can someone please tell me where I am going wrong and if there is a better way to do this?

+3


source to share


1 answer


In asynchronous programming, you only want to run the event loop (for example, IOLoop.start()

or reactor.run()

) once, at the top of your program. You are calling IOLoop.start()

, so instead of calling, reactor.run()

you want to tell Twisted to use Tornado IOLoop as your reactor. Before importing, reactor

do

import tornado.platform.twisted
tornado.platform.twisted.install()
from twisted.internet import reactor

      



See http://www.tornadoweb.org/en/stable/twisted.html#twisted-on-tornado for details .

Once you've done that, you can call the twisted libraries without having to start and stop the reactor.

+2


source







All Articles