Home>

I am currently studying asynchronous processing of python.
So I'm thinking of doing web scraping using asyncio, but I can't honestly understand the behavior of the program.

I would like to write a question based on the program below.
Would you please explain if you like?

import asyncio
from aiohttp import ClientSession
async def hello (url):
    async with ClientSession () as session:
        async with session.get (url) as response:
            response = await response.read ()
            print (response)
loop = asyncio.get_event_loop ()
loop.run_until_complete (hello ("http://httpbin.org/headers"))


I think that the function with async at the beginning is processed asynchronously.
async with ClientSession () as session:
async with session.get (url) as response:
I'm not sure how it works asynchronously.

When making await, I feel that the function with async is not called, so
Is it the idea that async is attached to a module that supports asynchronization from the outside (ClientSession etc.) and it is executed by await?

Sorry for the very confusing question. I looked around various sites, but I couldn't grasp it well, so I asked a question.

  • Answer # 1

    Below is the code that was rewritten synchronously.

    from requests import Session
    def hello (url):
        with Session () as session:
            with session.get (url) as response:
                response = response.raw.read ()
                print (response)
    hello ("http://httpbin.org/headers")

    with XYZ:In Case ofXYZ .__ enter__ ()WhenXYZ .__ exit__ ()Is called. On the other handasync with XYZ:In Case ofXYZ .__ aenter__ ()WhenXYZ .__ aexit__ ()ReturnsawaitableObjectawaitWill be done.

    If you can understand the synchronously rewritten code without any problem, I think you can understand it with this explanation.