python aiohttp和asyncio没有循环事件

时间:2019-02-25 20:16:57

标签: python python-asyncio aiohttp

我的理解是“异步定义”需要通过loop_event调用,例如

loop = asyncio.get_event_loop()
loop.run_until_complete(<method>)

我在下面创建了一些没有循环的代码。它仍然支持100个异步呼叫,没有问题。我有想念吗?

虚拟服务器休眠5秒。

from aiohttp import web
import asyncio
import time

async def hello(request):
    #time.sleep(1)
    await asyncio.sleep(5)
    return web.Response(text='dummy done')

app = web.Application()
app.add_routes([web.get('/', hello)])

web.run_app(app,host='127.0.0.1', port=8081)

实际服务器接受请求。

import json
from aiohttp import web
import aiohttp
import asyncio

n = 0

def mcowA(n):
   print (n, " : A") 
   return

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

def mcowB(n):
   print (n, " : B") 
   return

async def runMcows(request):
    global n
    n = n + 1
    mcowA(n)
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://localhost:8081')
    print(n,html)
    mcowB(n)
    return web.Response(text=html)

try:
    app = web.Application()
    app.add_routes([web.get('/', runMcows)])
    #loop = asyncio.get_event_loop(web.run_app(app))
    #loop.run_forever()
    web.run_app(app)
finally:
    loop.close()

1 个答案:

答案 0 :(得分:0)

user4815162342的评论将其钉住了。