鍍金池/ 問答/Python  網(wǎng)絡(luò)安全  HTML/ 協(xié)程的一點問題

協(xié)程的一點問題

代碼如下,index函數(shù)處理到達的請求,init 初始化服務(wù)器,剩下的為創(chuàng)建服務(wù)器的代碼

@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()

按照正常的思路,第一個請求到達后,index執(zhí)行至 yield處,會重新回到時間循環(huán),等待下一次循環(huán),但是真正執(zhí)行的時候 卻一直把index執(zhí)行完,才處理下一次請求。

圖片描述

回答
編輯回答
冷眸

這不是你的代碼問題,是瀏覽器的連接機制造成困擾。

自己寫一個客戶端測試便知,如

# -*- 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())
2017年9月29日 12:04