Search code examples
python-3.xtornado

confused about how the IOLoop in Tornado picks up the Application object


new to Tornado and trying to understand the fundamentals. given their sample application:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

I understand the application object has config values and RequestHandlers (basically the app behaviors) and I also understand the IOLoop to be some kind of wrapper around python3's asyncio module. Looking at the documentation for asyncio shows me this example:

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

Here asyncio is being told explicitly to run function main() whereas in the tornado example I'm not seeing where the event loop is being told to run the Application obj. How are the two associated?

been here and here already

ty!


Solution

  • Application.listen eventually calls into tornado.netutil.add_accept_handler, which registers on the current IOLoop via the IOLoop.current() static method.