Почему вылетает код, когда нет ответа с запроса requests get?
Есть код, который пингует сервера, и те, что отвечают на пинг - идет запрос через API. Написал цикл:
def NoStatsToday():
for x in Online:
url = 'http://' + x + ':8200/api/v1/detection_storage/get_detections_stat?datetime_start=' + today + 'T00:00:00%2B05:00&datetime_end=' + today + 'T23:59:59%2B05:00'
response = requests.get(url, timeout=5)
forparse = response.json()
all_detections = (forparse["statistic"]['all_detections'])
try:
response = requests.get(url, timeout=5)
except ConnectionError:
print(x + ' Нет подключение к порту 8200')
else:
if all_detections != 0:
print(x + ' Есть статистика')
else:
print(x + ' Нет статистики')
nostatsfile.write(x + pingfile.write(url + now))
Если порт 8200 недоступен, по идее должно писать
except ConnectionError:
print(x + ' Нет подключение к порту 8200')
Внес исправления, как посоветовал CrazyElf, если я правильно понял, имелось ввиду так:
def NoStatsToday():
for x in Online:
url = 'http://' + x + ':8200/api/v1/detection_storage/get_detections_stat?datetime_start=' + today + 'T00:00:00%2B05:00&datetime_end=' + today + 'T23:59:59%2B05:00'
try:
response = requests.get(url, timeout=5)
forparse = response.json()
all_detections = (forparse["statistic"]['all_detections'])
if all_detections != 0:
print(x + ' Есть статистика')
else:
print(x + ' Нет статистики')
nostatsfile.write(x + pingfile.write(url + now))
except ConnectionError:
print(x + ' Нет подключения к порту 8200')
Вроде сейчас не вылетает, прошу знающих проверить, остались ли еще какие то ошибки, из-за которых может неправильно отражаться данные или вылетать код ?
Ответы (1 шт):
Так всё нужно в try внести, чтобы except сработал:
url = 'http://' + x + ':8200/api/v1/detection_storage/get_detections_stat?datetime_start=' + today + 'T00:00:00%2B05:00&datetime_end=' + today + 'T23:59:59%2B05:00'
try:
response = requests.get(url, timeout=5)
forparse = response.json()
all_detections = (forparse["statistic"]['all_detections'])
except ConnectionError:
print(x + ' Нет подключение к порту 8200')
К чему у вас else относится я вообще не очень понял. К for? В любом случае вам нужно сделать какую-то инициализацию all_detections до цикла, иначе, если не будет ни одного успешного действия, у вас код упадёт на строке if all_detections != 0: