AttributeError: объект 'QuerySet' не имеет атрибута 'url'
в этом коде есть эта ошибка, и я совершенно не знаю, как ее исправить. код работает нормально, пока не дойдет до последнего объекта, сохраненного в базе данных, после чего выдает эту ошибку. код - это инструмент, который проверяет html сайта между двумя точками во времени, чтобы проверить, есть ли в нем ошибка, даже если сайт работает нормально и выдает код ответа 200
Это ошибка:
in check_html print(monitor.url) AttributeError: 'QuerySet' object has no attribute 'url'
`def run_monitors():
delete_from_db()
monitors = Monitor.objects.filter(is_active=True)
monitors._fetch_all()
asyncio.run(_run_monitors(monitors))
check_html(monitor=monitors)`
`def check_html(monitor):
start_time = time.time()
print(monitor.url)
# The URLs to compare
old_html = monitor.html_compare
new_url = monitor.url
# Get the HTML of each URL
try:
old_html = old_html
# html1.raise_for_status()
except Exception as e:
print(e)
try:
html2 = requests.get(new_url)
html2.raise_for_status()
except Exception as e:
print(e)
return None
html2 = html2.text[:10000]
# Create a SequenceMatcher object to compare the HTML of the two URLs
matcher = difflib.SequenceMatcher(None, old_html, html2)
similarity_ratio = matcher.ratio() * 100
response_time = time.time() - start_time
monitor.html_compare = html2
html_failure = False
counter = monitor.fault_counter
if similarity_ratio <= 90 and counter == 0:
print(f"The two HTMLs have {similarity_ratio:}% in common.")
print("change detected")
html_failure = False
counter += 1
elif similarity_ratio > 90 and counter == 0:
print(f"The two HTMLs have {similarity_ratio:.2f}% in common.")
print("no change detected")
html_failure = False
counter = 0
elif similarity_ratio > 90 and counter >= 1:
print(f"The two HTMLs have {similarity_ratio:.2f}% in common.")
if counter >= 4:
print(f"HTML fault detected")
html_failure = True
else:
counter += 1
print(f"checks if fault persists, current fault counter: {counter}")
elif similarity_ratio < 90 and counter >= 1:
print("Fault is presumably resolved")
html_failure = False
counter = 0
monitor.fault_counter = counter
# Print the similarity ratio between the two URLs
monitor.save(update_fields=['html_compare', 'fault_counter'])
return html_failure`
`def send_notifications():
for monitor in Monitor.objects.all():
multiple_failures, last_result = has_multiple_failures(monitor)
result = check_html(monitor)
no_notification_timeout = (not monitor.last_notified) or \
monitor.last_notified < timezone.now() - timedelta(hours=1)
if multiple_failures and no_notification_timeout and monitor.is_active:
_send_notification(monitor, last_result)
if result:
_send_notification(monitor, last_result)
`
Я уже пытался поставить цикл for вокруг функции 'check_html', которая итерирует каждый объект в мониторе, но это только возвращает, что мониторы не могут быть итерированы. это была долгая попытка, но все равно не сработало
Вы передали набор запросов в функцию check_html()
. Используя фильтр, мы получаем один или несколько элементов, которые можно итерировать. Вы можете использовать цикл for в функции check_html()
или передать в функцию только один объект.
все, я нашел проблему. поэтому я добавил функцию check_html для запуска по определенной команде. которая в конце скрипта пыталась отдать весь набор запросов самой функции check_html.
поэтому мне просто пришлось удалить функцию check_html из run_monitor.
спасибо за помощь, ребята