aiotk.AsyncExitStack
を知るいいきっかけになりました。
python
1from asyncio import get_event_loop
2from contextlib import closing
3
4from aiohttp import ClientSession
5from aiotk import AsyncExitStack
6
7
8async def main(*urls):
9 async with ClientSession() as sess:
10 async with AsyncExitStack() as stack:
11 responses = [await stack.enter_context(sess.get(url))
12 for url in urls]
13 if all(res.status == 200 for res in responses):
14 js1, js2, js3 = [await res.json() for res in responses]
15
16
17if __name__ == '__main__':
18 with closing(get_event_loop()) as loop:
19 loop.run_until_complete(main(
20 "https://AAAA",
21 "https://BBBB",
22 "https://CCCC",
23 ))
ライブラリのバージョン
C:\Users\sakurai>pip freeze | findstr "aiohttp aiotk"
aiohttp==2.2.3
aiotk==0.4.0
追記
多分こっち(asyncio.gather
)のほうがスマートかな。
python
1from asyncio import gather
2from asyncio import get_event_loop
3from contextlib import closing
4from operator import methodcaller as mcall
5
6from aiohttp import ClientSession
7from aiotk import AsyncExitStack
8
9
10async def main(*urls):
11 async with ClientSession() as sess:
12 async with AsyncExitStack() as stack:
13 coros = map(stack.enter_context, map(sess.get, urls))
14 responses = await gather(*coros)
15 if all(res.status == 200 for res in responses):
16 js1, js2, js3 = await gather(*map(mcall("json"), responses))
17
18
19if __name__ == '__main__':
20 with closing(get_event_loop()) as loop:
21 loop.run_until_complete(main(
22 "https://AAAA",
23 "https://BBBB",
24 "https://CCCC",
25 ))
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/01/21 09:40
2018/01/21 10:35
退会済みユーザー
2018/01/21 10:53 編集
2018/01/21 13:11
退会済みユーザー
2018/01/21 13:28