繁体   English   中英

异步运行事件循环,直到在 Python 中满足条件

[英]Async run event loop until condition is met in Python

我是 Async 的新手,我想创建一个脚本,每半秒执行一次请求以检查网站是否可用。 因此,即使网站响应时间像“4s”,它也会每 0.5 秒执行一次请求。 一旦其中一个请求收到“200”状态代码,事件循环就会中断。

URL = "https://stackoverflow.com"


async def load(session, url):
    async with session.get(url) as response:
        return await response.status == 200

async def create_session():
    complete = False
    while not complete:
        async with aiohttp.ClientSession() as session:
            task = await asyncio.create_task(load(session, URL))
            if task:
               break
            await asyncio.sleep(0.5)



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(create_session())

现在我得到了这样的东西,这显然是行不通的。

我能够使用asyncio.Event()创建所需的程序。

import asyncio
import aiohttp


url = "https://www.somesite.com"


async def load(session, url, flag):
     async with session.get(url) as response:
         if await response.status == 200: #Check if the site is available.
             flag.set() # Flag is set


async def create_session():
    flag = asyncio.Event()
    async with aiohttp.ClientSession() as session: # Create aiohttp Session
        while 1:
            asyncio.create_task(load(session, url, flag))
            await asyncio.sleep(0.5) # Wait 0.5 s between the requests
            if flag.is_set():# If flag is set then break the loop
                break


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(create_session())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM