【发布时间】:2019-01-22 07:39:54
【问题描述】:
我为一个看起来像这样的 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)?满足条件(状态码)如何取消处理?
【问题讨论】:
-
好的,当满足条件时,我设法取消了
raise StopIteration的执行,而不是await asyncio.gather(*tasks)我做await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)。如果有人知道更优雅的方式,请发布答案:) -
您可能想要提出除
StopIteration以外的其他内容——因为StopIteration被Python 使用,所以将其用作业务异常并不是一个好主意。我发布了一个答案,展示了如何使用Event进行同步。
标签: python python-3.x python-asyncio aiohttp