。
显然我需要一个服务器游标,因为它不可能将整个查询加载到内存中。
所以我有以下代码:
class QueryStreamer(RequestHandler):
def get(self):
cursor.execute("Select * from ...")
chunk = cursor.fetch(1000)
while chunk:
self.write(chunk)
self.flush()
chunk = cursor.fetch(1000)
self.finish()
cursor.close()
?,
。。
?
更新:答案中有以下建议我尝试了以下操作:
import tornado.ioloop
import tornado.web
import time
class PingHandler(tornado.web.RequestHandler):
def get(self):
for i in range(600):
self.write("pong\n")
self.flush()
time.sleep(1)
print "pong"
self.finish()
print "ponged"
def on_connection_close(self):
print "closed"
if __name__ == "__main__":
application = tornado.web.Application([ ("/ping", PingHandler), ])
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
I'm running this file in terminal 1 and in terminal 2 I invoke:
curl -s http://localhost:8888/ping
在第一次响应之后,我点击了CTRL-C,但是在终端1中,我看到它很高兴地保持着“pong”的状态,并且从来没有被调用过。
底线-仍然不起作用。
最佳答案
您需要使处理程序异步并使用ioloop.add_timeout
而不是time.sleep
,因为这会阻塞循环:
import tornado.ioloop
import tornado.web
import tornado.gen
class PingHandler(tornado.web.RequestHandler):
connection_closed = False
def on_connection_close(self):
print "closed"
self.connection_closed = True
@tornado.gen.coroutine # <= async handler
def get(self):
for i in range(600):
if self.connection_closed:
# `on_connection_close()` has been called,
# break out of the loop
break
self.write("pong %s\n" % i)
self.flush()
# Add a timeout. Similar to time.sleep(1), but non-blocking:
yield tornado.gen.Task(
tornado.ioloop.IOLoop.instance().add_timeout,
tornado.ioloop.IOLoop.instance().time() + 1,
)
self.finish()
print "finished"
if __name__ == "__main__":
application = tornado.web.Application([("/ping", PingHandler), ])
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
关于python - 如何在python-tornado中捕获写入异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19677777/