回答編集履歴
3
gatherに変更
test
CHANGED
@@ -70,9 +70,27 @@
|
|
70
70
|
|
71
71
|
# 追記
|
72
72
|
|
73
|
-
多分こっちのほうがスマートかな
|
73
|
+
多分こっち(`asyncio.gather`)のほうがスマートかな。
|
74
74
|
|
75
75
|
```python
|
76
|
+
|
77
|
+
from asyncio import gather
|
78
|
+
|
79
|
+
from asyncio import get_event_loop
|
80
|
+
|
81
|
+
from contextlib import closing
|
82
|
+
|
83
|
+
from operator import methodcaller as mcall
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
from aiohttp import ClientSession
|
88
|
+
|
89
|
+
from aiotk import AsyncExitStack
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
|
76
94
|
|
77
95
|
async def main(*urls):
|
78
96
|
|
@@ -82,10 +100,28 @@
|
|
82
100
|
|
83
101
|
coros = map(stack.enter_context, map(sess.get, urls))
|
84
102
|
|
85
|
-
responses =
|
103
|
+
responses = await gather(*coros)
|
86
104
|
|
87
105
|
if all(res.status == 200 for res in responses):
|
88
106
|
|
89
|
-
js1, js2, js3 =
|
107
|
+
js1, js2, js3 = await gather(*map(mcall("json"), responses))
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
|
112
|
+
|
113
|
+
if __name__ == '__main__':
|
114
|
+
|
115
|
+
with closing(get_event_loop()) as loop:
|
116
|
+
|
117
|
+
loop.run_until_complete(main(
|
118
|
+
|
119
|
+
"https://AAAA",
|
120
|
+
|
121
|
+
"https://BBBB",
|
122
|
+
|
123
|
+
"https://CCCC",
|
124
|
+
|
125
|
+
))
|
90
126
|
|
91
127
|
```
|
2
追記
test
CHANGED
@@ -65,3 +65,27 @@
|
|
65
65
|
aiotk==0.4.0
|
66
66
|
|
67
67
|
```
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
# 追記
|
72
|
+
|
73
|
+
多分こっちのほうがスマートかな(3.6以上限定)
|
74
|
+
|
75
|
+
```python
|
76
|
+
|
77
|
+
async def main(*urls):
|
78
|
+
|
79
|
+
async with ClientSession() as sess:
|
80
|
+
|
81
|
+
async with AsyncExitStack() as stack:
|
82
|
+
|
83
|
+
coros = map(stack.enter_context, map(sess.get, urls))
|
84
|
+
|
85
|
+
responses = [await task for task in as_completed(coros)]
|
86
|
+
|
87
|
+
if all(res.status == 200 for res in responses):
|
88
|
+
|
89
|
+
js1, js2, js3 = [await res.json() for res in responses]
|
90
|
+
|
91
|
+
```
|
1
もうちょっときれいに
test
CHANGED
@@ -18,7 +18,7 @@
|
|
18
18
|
|
19
19
|
|
20
20
|
|
21
|
-
async def main(urls):
|
21
|
+
async def main(*urls):
|
22
22
|
|
23
23
|
async with ClientSession() as sess:
|
24
24
|
|
@@ -40,7 +40,7 @@
|
|
40
40
|
|
41
41
|
with closing(get_event_loop()) as loop:
|
42
42
|
|
43
|
-
loop.run_until_complete(main(
|
43
|
+
loop.run_until_complete(main(
|
44
44
|
|
45
45
|
"https://AAAA",
|
46
46
|
|
@@ -48,7 +48,7 @@
|
|
48
48
|
|
49
49
|
"https://CCCC",
|
50
50
|
|
51
|
-
|
51
|
+
))
|
52
52
|
|
53
53
|
```
|
54
54
|
|