Understanding Asynchronous Programming in Python with Tornado and asyncio
This article explains the fundamentals of asynchronous programming, contrasting blocking, non‑blocking, synchronous and asynchronous execution, and demonstrates how to implement async behavior in Python using Tornado, asyncio, and aiohttp, including coroutine definitions, yield usage, and practical code examples.
In recent projects the author revisited asynchronous programming in Python, moving from Tornado on Python 2 to Python 3 and exploring coroutine usage in depth.
Basic concepts are introduced: blocking (the program waits and cannot do other work), non‑blocking (the program can continue while waiting), synchronous execution (ordered coordination of tasks), and asynchronous execution (tasks run independently without coordination).
Illustrative analogies compare cooking, laundry, and boiling water to show how synchronous processing wastes time, while asynchronous processing overlaps tasks to reduce total duration.
The article then shows how to implement these ideas in code, first with generator‑based coroutines using yield in Python 2, explaining that a function containing yield becomes a generator object.
It demonstrates the need for next() or send() to advance a generator, and explains the difference between them.
Moving to Python 3, the author introduces the async and await keywords, showing how an async def function returns a coroutine object that must be scheduled on an event loop.
Practical examples using the Tornado web framework illustrate synchronous request handling (with time.sleep ) and the problems it causes under load.
Solutions are presented: decorating handlers with @tornado.web.asynchronous and @tornado.gen.coroutine , offloading blocking calls to a thread pool via @run_on_executor , and finally using native asyncio features such as asyncio.sleep .
Because standard requests is not awaitable, the article switches to aiohttp for true asynchronous HTTP requests, demonstrating a complete async client‑server workflow that reduces total request time dramatically.
The conclusion emphasizes that asynchronous programming involves many concepts, varies across Python versions, and that mastering generators, coroutines, and async‑await is essential for building high‑performance, non‑blocking backend services.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.