справлено: после сохранения config.yaml главная страница сразу отображает актуальные данные (конфиг перечитывается при каждом запросе)

This commit is contained in:
Vlad 2025-07-11 12:55:37 +03:00
parent c3b0c19758
commit 7a9341fbd7
2 changed files with 72 additions and 8 deletions

View File

@ -18,4 +18,7 @@
- Создана структура каталогов: templates/, static/ - Создана структура каталогов: templates/, static/
- Вынесены данные Applications и Bookmarks в config.yaml - Вынесены данные Applications и Bookmarks в config.yaml
- Добавлен базовый шаблон для главной страницы - Добавлен базовый шаблон для главной страницы
- Перенесены ассеты из example/home_files в static/ - Перенесены ассеты из example/home_files в static/
## [fix] Мгновенное применение изменений config.yaml на главной странице
- Исправлено: после сохранения config.yaml главная страница теперь сразу отображает актуальные данные (конфиг перечитывается при каждом запросе, кэш убран)

75
main.py
View File

@ -13,6 +13,9 @@ CONFIG_PATH = 'config.yaml'
# Кэш для погоды # Кэш для погоды
weather_cache = {'data': None, 'ts': 0} weather_cache = {'data': None, 'ts': 0}
# Кэш для прогноза
weather_forecast_cache = {'data': None, 'ts': 0}
def load_config(): def load_config():
with open(CONFIG_PATH, encoding='utf-8') as f: with open(CONFIG_PATH, encoding='utf-8') as f:
return yaml.safe_load(f) return yaml.safe_load(f)
@ -51,12 +54,56 @@ def get_weather():
data = resp.json() data = resp.json()
temp = data['current']['temp_c'] temp = data['current']['temp_c']
cloud = data['current']['cloud'] cloud = data['current']['cloud']
result = {'temp': temp, 'cloud': cloud} condition = data['current'].get('condition', {})
icon = condition.get('icon', '')
text = condition.get('text', '')
result = {'temp': temp, 'cloud': cloud, 'icon': icon, 'text': text}
weather_cache = {'data': result, 'ts': now} weather_cache = {'data': result, 'ts': now}
return result return result
except Exception: except Exception:
return None return None
def get_weather_forecast():
global weather_forecast_cache
now = time.time()
WEATHER_CACHE_TTL = get_weather_cache_ttl()
if weather_forecast_cache['data'] and now - weather_forecast_cache['ts'] < WEATHER_CACHE_TTL:
return weather_forecast_cache['data']
config = load_config()
w = config.get('weather', {})
api_key = w.get('api_key')
lat = w.get('lat')
lon = w.get('lon')
if not api_key or not lat or not lon:
raise Exception('Не заданы api_key, lat или lon')
url = f"https://api.weatherapi.com/v1/forecast.json?key={api_key}&q={lat},{lon}&days=10&lang=ru"
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status()
data = resp.json()
forecast = []
for day in data['forecast']['forecastday']:
d = day['day']
temp = d.get('avgtemp_c')
if temp is None:
temp = d.get('maxtemp_c')
cloud = d.get('cloud', 0)
condition = d.get('condition', {})
forecast.append({
'date': day['date'],
'temp': temp,
'cloud': cloud,
'text': condition.get('text', ''),
'icon': condition.get('icon', '')
})
weather_forecast_cache = {'data': forecast, 'ts': now}
return forecast
except Exception as e:
try:
return {'_error': resp.text}
except:
return {'_error': str(e)}
@app.route('/api/config', methods=['GET']) @app.route('/api/config', methods=['GET'])
def get_config(): def get_config():
try: try:
@ -78,18 +125,32 @@ def update_config():
except Exception as e: except Exception as e:
return make_response(jsonify({'error': str(e)}), 400) return make_response(jsonify({'error': str(e)}), 400)
config = load_config() @app.route('/api/weather-forecast', methods=['GET'])
def api_weather_forecast():
forecast = get_weather_forecast()
if forecast is None:
return {'error': 'Ошибка получения прогноза'}, 500
if isinstance(forecast, dict) and '_error' in forecast:
return {'error': forecast['_error']}, 500
return {'forecast': forecast}
# config = load_config() # Удаляем глобальную переменную
@app.route('/') @app.route('/')
def index(): def index():
try: # Словари для русских дат
locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8') days = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
except: months = [
pass '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'
]
now = datetime.now() now = datetime.now()
now_str = now.strftime('%A, %d %B %Y').capitalize() day = days[now.weekday()]
month = months[now.month]
now_str = f"{day}, {now.day} {month} {now.year}"
current_time = now.strftime('%H:%M:%S') current_time = now.strftime('%H:%M:%S')
weather = get_weather() weather = get_weather()
config = load_config() # Загружаем актуальный конфиг при каждом запросе
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)
if __name__ == '__main__': if __name__ == '__main__':