3 Commits

3 changed files with 1700 additions and 1498 deletions

67
app.py
View File

@@ -1,4 +1,4 @@
from flask import Flask, render_template, request, redirect, url_for, session, abort, jsonify, g
from flask import Flask, render_template, request, redirect, url_for, session, abort, jsonify, g, make_response
from flask_babel import Babel, gettext, ngettext, get_locale
from datetime import datetime, timedelta
import numpy as np
@@ -20,7 +20,23 @@ app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations'
babel = Babel()
# Version der App
APP_VERSION = "1.4.9"
APP_VERSION = "1.4.11"
def add_cache_headers(response):
"""Fügt Cache-Control-Header hinzu, die den Back-Forward-Cache ermöglichen"""
# Cache-Control für statische Inhalte und API-Endpunkte
if request.path.startswith('/static/') or request.path.startswith('/api/'):
response.headers['Cache-Control'] = 'public, max-age=3600, s-maxage=3600'
else:
# Für HTML-Seiten: kurze Cache-Zeit, aber Back-Forward-Cache erlauben
response.headers['Cache-Control'] = 'public, max-age=60, s-maxage=300'
# Wichtig: Keine Vary-Header für User-Agent oder andere dynamische Werte
# Dies verhindert den Back-Forward-Cache
if 'Vary' in response.headers:
del response.headers['Vary']
return response
# HTML-Template wird jetzt aus templates/index.html geladen
@@ -229,9 +245,10 @@ def index():
plusminus_result = f"Datum {d.strftime('%d.%m.%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} Monate: {result.strftime('%d.%m.%Y')}"
except Exception:
plusminus_result = gettext('Ungültige Eingabe')
return render_template('index.html', tage=tage, werktage=werktage, wochentag=wochentag, plusminus_result=plusminus_result, kw_berechnen=kw_berechnen, kw_datum=kw_datum, active_idx=active_idx
response = make_response(render_template('index.html', tage=tage, werktage=werktage, wochentag=wochentag, plusminus_result=plusminus_result, kw_berechnen=kw_berechnen, kw_datum=kw_datum, active_idx=active_idx
, feiertage_anzahl=feiertage_anzahl, wochenendtage_anzahl=wochenendtage_anzahl, app_version=APP_VERSION, get_locale=get_locale
)
))
return add_cache_headers(response)
def parse_log_stats(log_path):
@@ -304,11 +321,14 @@ def stats():
session['stats_auth'] = True
return redirect(url_for('stats'))
else:
return render_template('stats_login.html', error='Falsches Passwort!')
return render_template('stats_login.html', error=None)
response = make_response(render_template('stats_login.html', error='Falsches Passwort!'))
return add_cache_headers(response)
response = make_response(render_template('stats_login.html', error=None))
return add_cache_headers(response)
log_path = os.path.join('log', 'pageviews.log')
pageviews, func_counts, func_counts_hourly, impressions_per_day, impressions_per_hour, api_counts, api_counts_hourly = parse_log_stats(log_path)
return render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, func_counts_hourly=func_counts_hourly, impressions_per_day=impressions_per_day, impressions_per_hour=impressions_per_hour, api_counts=api_counts, api_counts_hourly=api_counts_hourly)
response = make_response(render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, func_counts_hourly=func_counts_hourly, impressions_per_day=impressions_per_day, impressions_per_hour=impressions_per_hour, api_counts=api_counts, api_counts_hourly=api_counts_hourly))
return add_cache_headers(response)
# --- REST API ---
def log_api_usage(api_name):
@@ -342,7 +362,8 @@ def api_tage_werktage():
tage = int(np.busday_count(d1.date(), (d2 + timedelta(days=1)).date(), holidays=holidays))
else:
tage = abs((d2 - d1).days)
return jsonify({'result': tage})
response = jsonify({'result': tage})
return add_cache_headers(response)
except Exception as e:
return jsonify({'error': 'Ungültige Eingabe', 'details': str(e)}), 400
@@ -355,7 +376,8 @@ def api_wochentag():
d = datetime.strptime(datum, '%Y-%m-%d')
wochentage = get_wochentage()
wochentag = wochentage[d.weekday()]
return jsonify({'result': wochentag})
response = jsonify({'result': wochentag})
return add_cache_headers(response)
except Exception as e:
return jsonify({'error': 'Ungültige Eingabe', 'details': str(e)}), 400
@@ -372,7 +394,8 @@ def api_kw_berechnen():
kw_berechnen = f"Week {kw} ({d.year})"
else:
kw_berechnen = f"KW {kw} ({d.year})"
return jsonify({'result': kw_berechnen, 'kw': kw, 'jahr': d.year})
response = jsonify({'result': kw_berechnen, 'kw': kw, 'jahr': d.year})
return add_cache_headers(response)
except Exception as e:
return jsonify({'error': 'Ungültige Eingabe', 'details': str(e)}), 400
@@ -392,7 +415,8 @@ def api_kw_datum():
kw_datum = f"{start.strftime('%m/%d/%Y')} to {end.strftime('%m/%d/%Y')}"
else:
kw_datum = f"{start.strftime('%d.%m.%Y')} bis {end.strftime('%d.%m.%Y')}"
return jsonify({'result': kw_datum, 'start': start.strftime('%Y-%m-%d'), 'end': end.strftime('%Y-%m-%d')})
response = jsonify({'result': kw_datum, 'start': start.strftime('%Y-%m-%d'), 'end': end.strftime('%Y-%m-%d')})
return add_cache_headers(response)
except Exception as e:
return jsonify({'error': 'Ungültige Eingabe', 'details': str(e)}), 400
@@ -415,22 +439,26 @@ def api_plusminus():
if is_werktage:
result = np.busday_offset(d.date(), anzahl_int, roll='forward')
result_dt = datetime.strptime(str(result), '%Y-%m-%d')
return jsonify({'result': result_dt.strftime('%Y-%m-%d')})
response = jsonify({'result': result_dt.strftime('%Y-%m-%d')})
return add_cache_headers(response)
else:
result = d + timedelta(days=anzahl_int)
return jsonify({'result': result.strftime('%Y-%m-%d')})
response = jsonify({'result': result.strftime('%Y-%m-%d')})
return add_cache_headers(response)
elif einheit == 'wochen':
if is_werktage:
return jsonify({'error': 'Nicht unterstützt: Werktage + Wochen.'}), 400
else:
result = d + timedelta(weeks=anzahl_int)
return jsonify({'result': result.strftime('%Y-%m-%d')})
response = jsonify({'result': result.strftime('%Y-%m-%d')})
return add_cache_headers(response)
elif einheit == 'monate':
if is_werktage:
return jsonify({'error': 'Nicht unterstützt: Werktage + Monate.'}), 400
else:
result = d + relativedelta(months=anzahl_int)
return jsonify({'result': result.strftime('%Y-%m-%d')})
response = jsonify({'result': result.strftime('%Y-%m-%d')})
return add_cache_headers(response)
else:
return jsonify({'error': 'Ungültige Einheit'}), 400
except Exception as e:
@@ -440,12 +468,13 @@ def api_plusminus():
def api_stats():
log_path = os.path.join('log', 'pageviews.log')
pageviews, func_counts, func_counts_hourly, impressions_per_day, impressions_per_hour, api_counts, api_counts_hourly = parse_log_stats(log_path)
return jsonify({
response = jsonify({
"pageviews": pageviews,
"func_counts": func_counts,
"impressions_per_day": impressions_per_day,
"api_counts": api_counts
})
return add_cache_headers(response)
@app.route('/api/monitor', methods=['GET'])
def api_monitor():
@@ -457,17 +486,19 @@ def api_monitor():
if 'PAGEVIEW' in line:
pageviews += 1
uptime = int(time.time() - app_start_time)
return jsonify({
response = jsonify({
"status": "ok",
"message": "App running",
"time": datetime.now().isoformat(),
"uptime_seconds": uptime,
"pageviews_last_7_days": pageviews
})
return add_cache_headers(response)
@app.route('/api-docs')
def api_docs():
return render_template('swagger.html')
response = make_response(render_template('swagger.html'))
return add_cache_headers(response)
if __name__ == '__main__':

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
.v{
{
"openapi": "3.0.3",
"info": {
"title": "Elpatrons Datumsrechner API",