gpt4 book ai didi

Python aiohttp : cancel async execution on met condition

转载 作者:行者123 更新时间:2023-12-01 01:16:24 35 4
gpt4 key购买 nike

我为 CTF 游戏编写了一个异步暴力破解脚本,如下所示

async def bound_fetch(sem, session, answer):
# generating url, headers and json ...
async with sem, session.post(url=url, json=json, headers=headers) as response:
if response.status == 200:
print('Right answer found: %s' % json['answer'])


async def run(words):
tasks = []
sem = asyncio.Semaphore(3)
async with aiohttp.ClientSession() as session:
for word in words:
task = asyncio.create_task(bound_fetch(sem=sem, session=session, answer=''.join(word)))
tasks.append(task)
print("Generated %d possible answers. Checking %s" % (len(tasks), base_url))
await asyncio.gather(*tasks)


if __name__ == '__main__':
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(possible_answers))
loop.run_until_complete(future)

我的引用是本教程:https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html

我想知道这是否是在 aiohttp 中执行此操作的正确方法,或者我是否使事情变得太复杂(因为我不需要处理所有响应,只需知道哪个响应的状态为 200)?当满足条件(状态代码)时如何取消处理?

最佳答案

I was wondering if this is the right way to do it in aiohttp

您的代码相本地道。在顶层,您可以省略 asyncio.ensure_future 并简单地调用 asyncio.run(run(possible_answers))

How do I cancel the processing when the condition (status code) is met?

您可以使用事件或 future 对象并等待它,而不是使用gather。您可能知道,运行协程不需要 gather(它们按照 create_task 的计划立即运行),其明确目的就是等待所有协程完成。基于事件的同步可能如下所示:

async def bound_fetch(sem, session, answer, done):
# generating url, headers and json ...
async with sem, session.post(url=url, json=json, headers=headers) as response:
if response.status == 200:
done.set()
done.run_answer = json['answer']

async def run(words):
sem = asyncio.Semaphore(3)
done = asyncio.Event()
async with aiohttp.ClientSession() as session:
tasks = []
for word in words:
tasks.append(asyncio.create_task(bound_fetch(
sem=sem, session=session, answer=''.join(word), done=done)))
print("Generated %d possible answers. Checking %s" % (len(words), base_url))
await done.wait()
print('Right answer found: %s' % done.run_answer)
for t in tasks:
t.cancel()

关于Python aiohttp : cancel async execution on met condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54303367/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com