5
5
from pprint import pprint
6
6
import os
7
7
import time
8
+ import aiohttp
8
9
9
10
# Import app libraries
10
11
from switchmap import API_POLLER_POST_URI
@@ -58,14 +59,14 @@ async def devices(max_concurrent_devices=None):
58
59
# Semaphore to limit concurrent devices
59
60
device_semaphore = asyncio .Semaphore (max_concurrent_devices )
60
61
61
- tasks = [
62
- device ( argument , device_semaphore , post = True ) for argument in arguments
63
- ]
64
-
65
- # Execute all devices concurrently
66
- start_time = time .time ()
67
- results = await asyncio .gather (* tasks , return_exceptions = True )
68
- end_time = time .time ()
62
+ async with aiohttp . ClientSession () as session :
63
+ tasks = [
64
+ device ( argument , device_semaphore , session , post = True ) for argument in arguments
65
+ ]
66
+ # Execute all devices concurrently
67
+ start_time = time .time ()
68
+ results = await asyncio .gather (* tasks , return_exceptions = True )
69
+ end_time = time .time ()
69
70
70
71
# Process results and log summary
71
72
success_count = sum (1 for r in results if r is True )
@@ -83,7 +84,7 @@ async def devices(max_concurrent_devices=None):
83
84
log .log2warning (1403 , log_message )
84
85
85
86
86
- async def device (poll_meta , device_semaphore , post = True ):
87
+ async def device (poll_meta , device_semaphore , session , post = True ):
87
88
"""Poll each device asynchoronously.
88
89
89
90
Args:
@@ -137,13 +138,20 @@ async def device(poll_meta, device_semaphore, post=True):
137
138
data = _device .process ()
138
139
data ["misc" ]["zone" ] = zone
139
140
140
- #! do a little research on aiohttp
141
141
if post :
142
- rest .post (API_POLLER_POST_URI , data , config )
143
- log_message = (
144
- f"Successfully polled and posted data for { hostname } "
145
- )
146
- log .log2debug (1407 , log_message )
142
+ try :
143
+ async with session .post (API_POLLER_POST_URI , json = data ) as res :
144
+ if res .status == 200 :
145
+ log_message = f"Successfully polled and posted data for { hostname } "
146
+ log .log2debug (1407 , log_message )
147
+ else :
148
+ log_message = f"Failed to post data for { hostname } , status={ res .status } "
149
+ log .log2warning (1414 , log_message )
150
+ except aiohttp .ClientError as e :
151
+ log_message = f"HTTP error posting data for { hostname } : { e } "
152
+ log .log2exception (1415 , log_message )
153
+ return False
154
+
147
155
else :
148
156
pprint (data )
149
157
@@ -192,8 +200,9 @@ async def cli_device(hostname):
192
200
log .log2info (1410 , log_message )
193
201
194
202
# Poll each zone occurrence
203
+ semaphore = asyncio .Semaphore (1 )
195
204
tasks = [
196
- device (argument , asyncio . Semaphore ( 1 ) , post = False )
205
+ device (argument , semaphore , post = False )
197
206
for argument in arguments
198
207
]
199
208
results = await asyncio .gather (* tasks , return_exceptions = True )
0 commit comments