homepage/main.py

90 lines
2.6 KiB
Python

from flask import Flask, render_template, request, jsonify, make_response
import yaml
from datetime import datetime
import os
import requests
import time
app = Flask(__name__)
CONFIG_PATH = 'config.yaml'
# Кэш для погоды
weather_cache = {'data': None, 'ts': 0}
def load_config():
with open(CONFIG_PATH, encoding='utf-8') as f:
return yaml.safe_load(f)
def save_config(yaml_text):
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
f.write(yaml_text)
def get_weather_cache_ttl():
config = load_config()
w = config.get('weather', {})
ttl = w.get('cache_ttl')
try:
return int(ttl) * 60 if ttl else 3600
except Exception:
return 3600
def get_weather():
global weather_cache
now = time.time()
WEATHER_CACHE_TTL = get_weather_cache_ttl()
if weather_cache['data'] and now - weather_cache['ts'] < WEATHER_CACHE_TTL:
return weather_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:
return None
url = f"https://api.weatherapi.com/v1/current.json?key={api_key}&q={lat},{lon}&lang=ru"
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status()
data = resp.json()
temp = data['current']['temp_c']
cloud = data['current']['cloud']
result = {'temp': temp, 'cloud': cloud}
weather_cache = {'data': result, 'ts': now}
return result
except Exception:
return None
@app.route('/api/config', methods=['GET'])
def get_config():
try:
with open(CONFIG_PATH, encoding='utf-8') as f:
content = f.read()
return jsonify({'content': content})
except Exception as e:
return make_response(jsonify({'error': str(e)}), 500)
@app.route('/api/config', methods=['POST'])
def update_config():
data = request.get_json()
yaml_text = data.get('content', '')
try:
# Проверка валидности yaml
yaml.safe_load(yaml_text)
save_config(yaml_text)
return jsonify({'status': 'ok'})
except Exception as e:
return make_response(jsonify({'error': str(e)}), 400)
config = load_config()
@app.route('/')
def index():
now = datetime.now().strftime('%A, %d %B %Y - %H:%M:%S')
weather = get_weather()
return render_template('index.html', applications=config['applications'], bookmarks=config['bookmarks'], now=now, weather=weather)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')