Sobes.tech
Middle+

Is writing to disk and requesting a third-party service blocking or not? How does asyncio handle this?

sobes.tech AI

Answer from AI

Writing to disk and requests to third-party services are usually blocking operations, as they depend on external resources and can take an indefinite amount of time.

In asyncio, such operations should be performed asynchronously to avoid blocking the event loop. For this, you can use:

  • Asynchronous libraries that implement non-blocking I/O (for example, aiohttp for HTTP requests).
  • For blocking operations that do not have an asynchronous equivalent, you can use run_in_executor to run them in a separate thread or process.

Example:

import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    html = await fetch('http://example.com')
    print(html)

asyncio.run(main())

For writing to disk, you can use aiofiles — an asynchronous library for working with files.