在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

協(xié)程的一點(diǎn)問(wèn)題

代碼如下,index函數(shù)處理到達(dá)的請(qǐng)求,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()

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

圖片描述

回答
編輯回答
冷眸

這不是你的代碼問(wèn)題,是瀏覽器的連接機(jī)制造成困擾。

自己寫(xiě)一個(gè)客戶端測(cè)試便知,如

# -*- 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