0

The interface for sending requests synchronously is very simple:

# using requests package
content = requests.get('http://www.example.com').content

# using httpx package:
content = httpx.get('http://www.example.com').content

However, when sending requests asynchronously, it gets a bit more complex:

# using aiohttp package
async with aiohttp.ClientSession() as session:
    async with session.get('http://www.example.org') as response:
        content = await response.text()

# using httpx package
async with httpx.AsyncClient() as client:
    response = await client.get('http://www.example.org')
    content = response.content

Why must we use these Client objects when sending asynchronous requests? Why can't the interface be as simple as when sending synchronous requests:

# using imaginary package
response = await aiopackage.get('http://www.example.com')
content = response.content
tomerm98
  • 31
  • 2

1 Answers1

0

I think the answer to this question is rooted in design patterns. The case with context managers (sync and async) is related to 'Inversion of Control' and 'Dependency Injection'. It provides a systematic and uniform way of managing resources (encapsulated in various promise objects in case of async)

Of course, the patterns that you seek can be built by writing your own abstraction on top of what various libraries already provide.

Arnab De
  • 402
  • 4
  • 12