Last active
February 16, 2022 07:15
Revisions
-
Steve Peak revised this gist
Jan 13, 2013 . 1 changed file with 29 additions and 34 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,34 +1,29 @@ from time import sleep from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, asynchronous, RequestHandler from multiprocessing.pool import ThreadPool _workers = ThreadPool(10) def run_background(func, callback, args=(), kwds={}): def _callback(result): IOLoop.instance().add_callback(lambda: callback(result)) _workers.apply_async(func, args, kwds, _callback) # blocking task like querying to MySQL def blocking_task(n): sleep(n) return n class Handler(RequestHandler): @asynchronous def get(self): run_background(blocking_task, self.on_complete, (10,)) def on_complete(self, res): self.write("Test {0}<br/>".format(res)) self.finish() HTTPServer(Application([("/", Handler)],debug=True)).listen(8888) IOLoop.instance().start() -
Steve Peak created this gist
Jan 12, 2013 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ import tornado.ioloop import tornado.web import time class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self, request): if request is None: self.application.go = False self.write("Waiting for GET @ http://localhost:8888/go...<br>") self.flush() self._do_wait() else: self.application.go = True self.finish('Thanks!') def _do_wait(self, timeout_trys=10): if self.application.go: self.write('Finish') self.finish() else: self.write("Sleeping 2 second, timeout_trys=%s<br>" % timeout_trys) self.flush() tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 2, lambda: self._do_wait(timeout_trys-1)) application = tornado.web.Application([ (r"/(\w+)?", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()