I am pretty new to Tornado. I can't understand the difference between using run_on_executor
and defining an async
method. Is it the same? Is the one multithreaded and the other not?
Thank you in advance.
run_on_executor
is for interfacing with blocking non-async code.
You are correct that async code is only executed in a single thread. Maybe an example would illustrate the point.
Let's say your Tornado web service interfaces with a library that makes use of requests
to fetch country info for a given IP address. Since requests
is a non-async library, calling this function would block the Tornado event loop.
So, you have two options: try to find the replacement for the library that is async-compatible OR run the blocking code in a different thread/process and have your event loop await
its result like for normal async code without blocking the event loop. The latter option is run_on_executor
which allows you to run the task in different thread or process, and asyncio would "await" its completion.