Last active
February 16, 2022 07:15
-
-
Save stevepeak/4520732 to your computer and use it in GitHub Desktop.
Tornado Long-Polling Example
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 characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from http://tornadogists.org/2185380/