ндикатор статуса сервисов теперь асинхронный, не тормозит загрузку страницы

This commit is contained in:
Vlad 2025-07-11 14:17:48 +03:00
parent 3c813fa0b1
commit c473db7050
3 changed files with 32 additions and 11 deletions

View File

@ -25,4 +25,7 @@
## [feature] Индикатор статуса сервисов на главной странице ## [feature] Индикатор статуса сервисов на главной странице
- Добавлен индикатор (зелёный/красный квадратик после даты) для отображения доступности всех сервисов из config.yaml (включая Uptime Kuma) - Добавлен индикатор (зелёный/красный квадратик после даты) для отображения доступности всех сервисов из config.yaml (включая Uptime Kuma)
- Проверка доступности реализована через HTTP-запросы при каждом открытии главной страницы - Проверка доступности реализована через HTTP-запросы при каждом открытии главной страницы
## [improve] Асинхронный индикатор статуса сервисов
- Индикатор статуса сервисов теперь обновляется асинхронно через отдельный API-эндпоинт, не тормозит загрузку страницы

13
main.py
View File

@ -6,6 +6,7 @@ import requests
import time import time
import locale import locale
import socket import socket
from threading import Thread
app = Flask(__name__) app = Flask(__name__)
@ -151,6 +152,13 @@ def api_weather_forecast():
return {'error': forecast['_error']}, 500 return {'error': forecast['_error']}, 500
return {'forecast': forecast} return {'forecast': forecast}
@app.route('/api/services-status', methods=['GET'])
def api_services_status():
config = load_config()
services = config.get('services', [])
status = check_services_status(services) if services else None
return jsonify({'all_services_up': status})
# config = load_config() # Удаляем глобальную переменную # config = load_config() # Удаляем глобальную переменную
@app.route('/') @app.route('/')
@ -168,9 +176,8 @@ def index():
current_time = now.strftime('%H:%M:%S') current_time = now.strftime('%H:%M:%S')
weather = get_weather() weather = get_weather()
config = load_config() # Загружаем актуальный конфиг при каждом запросе config = load_config() # Загружаем актуальный конфиг при каждом запросе
services = config.get('services', []) # Убираем all_services_up из рендера
all_services_up = check_services_status(services) if services else None return render_template('index.html', applications=config['applications'], bookmarks=config['bookmarks'], now=now_str, current_time=current_time, weather=weather)
return render_template('index.html', applications=config['applications'], bookmarks=config['bookmarks'], now=now_str, current_time=current_time, weather=weather, all_services_up=all_services_up)
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0') app.run(debug=True, host='0.0.0.0')

View File

@ -29,13 +29,7 @@
<div style="display:flex; flex-direction:row; align-items:center; gap:12px;"> <div style="display:flex; flex-direction:row; align-items:center; gap:12px;">
<span style="font-size:1.6em; color: var(--color-primary);">{{ current_time }}</span> <span style="font-size:1.6em; color: var(--color-primary);">{{ current_time }}</span>
<span style="font-size:1.6em; color: var(--color-primary);">{{ now }}</span> <span style="font-size:1.6em; color: var(--color-primary);">{{ now }}</span>
{% if all_services_up is not none %} <span id="services-status-indicator" title="Статус сервисов" style="display:inline-block; width:18px; height:18px; border-radius:4px; margin-left:8px; background:#888; border:1.5px solid #444;"></span>
{% if all_services_up %}
<span title="Статус сервисов" style="display:inline-block; width:18px; height:18px; border-radius:4px; margin-left:8px; background:#2ecc40; border:1.5px solid #444;"></span>
{% else %}
<span title="Статус сервисов" style="display:inline-block; width:18px; height:18px; border-radius:4px; margin-left:8px; background:#ff4136; border:1.5px solid #444;"></span>
{% endif %}
{% endif %}
</div> </div>
<div class="WeatherWidget_WeatherWidget__3XlYt" id="weather-area" style="cursor:pointer;"> <div class="WeatherWidget_WeatherWidget__3XlYt" id="weather-area" style="cursor:pointer;">
<div> <div>
@ -228,6 +222,23 @@ weatherArea.onclick = function() {
closeForecastBtn.onclick = function() { closeForecastBtn.onclick = function() {
forecastModal.style.display = 'none'; forecastModal.style.display = 'none';
}; };
window.addEventListener('DOMContentLoaded', function() {
const indicator = document.getElementById('services-status-indicator');
if (indicator) {
fetch('/api/services-status').then(r => r.json()).then(data => {
if (data.all_services_up === true) {
indicator.style.background = '#2ecc40';
} else if (data.all_services_up === false) {
indicator.style.background = '#ff4136';
} else {
indicator.style.background = '#888';
}
}).catch(() => {
indicator.style.background = '#888';
});
}
});
</script> </script>
</body> </body>
</html> </html>