Last active
July 31, 2017 15:43
-
-
Save dineshprabu-freshdesk/aca8615ecef08970e89478b15ad9ef24 to your computer and use it in GitHub Desktop.
[Python] Tornado 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.web | |
from tornado.ioloop import IOLoop | |
from tornado import gen | |
from tornado.concurrent import run_on_executor | |
from concurrent.futures import ThreadPoolExecutor | |
MAX_WORKERS = 16 | |
class TestHandler(tornado.web.RequestHandler): | |
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS) | |
""" | |
In below function goes your time consuming task | |
""" | |
@run_on_executor | |
def background_task(self): | |
sm = 0 | |
for i in range(10 ** 8): | |
sm = sm + 1 | |
return sm | |
@gen.coroutine | |
def get(self): | |
""" Request that asynchronously calls background task. """ | |
res = yield self.background_task() | |
self.write(str(res)) | |
class TestHandler2(tornado.web.RequestHandler): | |
@gen.coroutine | |
def get(self): | |
self.write('Response from server') | |
self.finish() | |
application = tornado.web.Application([ | |
(r"/A", TestHandler), | |
(r"/B", TestHandler2), | |
]) | |
application.listen(5000) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment