【发布时间】:2018-04-20 04:50:24
【问题描述】:
这是我的代码:
import asyncio
import logging
import time
from aiohttp import web
logging.getLogger('aiohttp').setLevel(logging.DEBUG)
logging.getLogger('aiohttp').addHandler(logging.StreamHandler(sys.stderr))
def handle_sync(request):
web.web_logger.debug('Sync begin')
time.sleep(10)
web.web_logger.debug('Sync end')
return web.Response(text='Synchronous hello')
async def handle_async(request):
web.web_logger.debug('Async begin')
await asyncio.sleep(10)
web.web_logger.debug('Async end')
return web.Response(text='Asynchronous hello')
async def init(loop):
app = web.Application(loop=loop)
app.router.add_get('/sync/', handle_sync)
app.router.add_get('/async/', handle_async)
srv = await loop.create_server(app.make_handler(), '0.0.0.0', 8080)
return srv
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
我希望有两种行为:
- 当点击两次
/sync/url 时,假设间隔为 2 秒,总时间为 20 秒,因为我们在一个线程中有一个服务器,并且有一个阻塞调用 - 以相同方式点击两次
/async/url 的总时间为 12 秒(这些调用是异步的,对吗?)
但这两种情况似乎都持续了 20 秒,有人可以解释一下原因吗?
【问题讨论】:
标签: async-await python-asyncio aiohttp