I want to implement a web service based on tornado which can provide the database query service for users. I used the pyodbc module to connect to database and do the query. In practice, I found that printing the query result would take a long time. That is to say, if I used the following code to print the query result
while 1:
data = cursor.fetchone()
if not data: break
self.write(data + '\n')
self.flush()
and the sql command is something like
select * from <a large dummy table>
tornado would not print the query result until the loop is over. And it takes a long time.
I wanna make use of tornado's non-blocking asynchronous feature to make other users also be able to use the web service even though the loop for printing the current user's query request is not finished yet.
So I write something like:
@tornado.web.asynchronous
def get(self):
try:
cnxn = pyodbc.connect(self.server, self.driver, self.table, self.uid, self.pwd)
except Exception, e:
print e
return
try:
self.cur = cnxn.execute(self.sql)
except Exception, e:
print e
return
self.wait_for_query(callback=self.async_callback(self.on_finish))
def wait_for_query(self, callback):
while 1:
data = self.cur.fetchone()
if not data: break
self.write(data)
self.flush()
callback()
def on_finish(self):
self.finish()
I read this post: Asynchronous COMET query with Tornado and Prototype and knew my solution wouldn't work. But I certainly cannot use add_timeout, 'cause there is no way for me to figure out how long an iteration would last. So how can I work through this to achieve my goal?