即使使用asyncio和aiohttp,方法也会等待请求响应

时间:2018-12-30 15:32:29

标签: python asynchronous python-asyncio aiohttp

嗨,我有以下问题,我想执行getlastItemFromGivenInterval方法,让它简短地进行处理而无需等待请求响应,并为asyncio.sleep(60)提供上下文以在60秒内再次执行整个过程时间范围。我得到的是在getLastItemFromGivenInterval()中等待请求结束。

import aiohttp
import asyncio

loop = asyncio.get_event_loop()
task = loop.create_task(main())
loop.run_forever()

async def main():
    async with aiohttp.ClientSession() as session:
        while True:
            await bc.getLastItemFromGivenInterval(session)
            await asyncio.sleep(60)

async def getLastItemFromGivenInterval(session):
    async with session.get(BinanceClient.base_endpoint + "/api/v1/time") as currentServerTime:
        currentServerTime = await currentServerTime.json()
        currentServerTime = currentServerTime['serverTime']

    async with session.get(url) as res:
        response = await res.json()
        array = []
        print(response)

        return response

getLastItemFromGivenInterval放在单独的类中。 请给我一个提示,如何在getLastItem ...()方法中实现不等待的效果。

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您希望在后台启动getLastItemFromGivenInterval,并且每60秒执行一次,无论完成需要多长时间。您可以将await替换为create_task,然后再也不必等待生成的任务:

loop = asyncio.get_event_loop()
while True:
    # spawn the task in the background, and proceed
    loop.create_task(bc.getLastItemFromGivenInterval(session))
    # wait 60 seconds, allowing the above task (and other
    # tasks managed by the event loop) to run
    await asyncio.sleep(60)

您可能还需要确保完成较长时间或无限期挂起(例如由于网络故障)的任务不会堆积:

loop = asyncio.get_event_loop()
while True:
    # asyncio.wait_for will cancel the task if it takes longer
    # than the specified duration
    loop.create_task(asyncio.wait_for(
        bc.getLastItemFromGivenInterval(session), 500))
    await asyncio.sleep(60)