A problem with the cooperative process

The

code is as follows. The index function handles the incoming request, init initializes the server, and the rest is the code to create the server

@asyncio.coroutine
def index(request):
    print("one connection come...")
    yield from asyncio.sleep(10)
    return web.Response(body=b"<h1>Awesome</h1>",content_type="text/html")

@asyncio.coroutine
def init(loop):
    app=web.Application(loop=loop)

    app.router.add_route("GET","/",index)

    
    srv=yield from  loop.create_server(app.make_handler(),"127.0.0.1",9000)
    logging.info("server start at ")
    return srv


loop=asyncio.get_event_loop()

loop.run_until_complete(init(loop))

loop.run_forever()

according to normal thinking, after the first request arrives, the index executes to the yield and returns to the time loop and waits for the next loop, but when it is actually executed, the index is executed all the time before the next request is processed.

Mar.23,2021

it's not your code, it's the browser's connection mechanism.

write a client test yourself, such as

-sharp -*- coding: utf-8 -*-
import aiohttp
import asyncio


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


async def main():
    async with aiohttp.ClientSession() as session:
        htmls = await asyncio.gather(
            fetch(session, 'http://localhost:9000/'),
            fetch(session, 'http://localhost:9000/'),
        )
        print(htmls)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Menu