209 lines
8.6 KiB
Python
209 lines
8.6 KiB
Python
from flask import Flask, render_template, request, redirect, url_for, session, abort, jsonify
|
|
from datetime import datetime, timedelta
|
|
import numpy as np
|
|
from dateutil.relativedelta import relativedelta
|
|
import os
|
|
import time
|
|
|
|
app_start_time = time.time()
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = os.environ.get('SECRET_KEY', 'dev-key')
|
|
|
|
# HTML-Template wird jetzt aus templates/index.html geladen
|
|
|
|
WOCHENTAGE = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"]
|
|
|
|
@app.route('/', methods=['GET', 'POST'])
|
|
def index():
|
|
# Rudimentäres Logging für Page Impressions
|
|
log_dir = 'log'
|
|
os.makedirs(log_dir, exist_ok=True)
|
|
log_path = os.path.join(log_dir, 'pageviews.log')
|
|
# Logfile bereinigen: nur Zeilen der letzten 7 Tage behalten
|
|
if os.path.exists(log_path):
|
|
now = datetime.now()
|
|
lines_new = []
|
|
with open(log_path, encoding='utf-8') as f:
|
|
for line in f:
|
|
try:
|
|
date_str = line[:10]
|
|
date = datetime.strptime(date_str, '%Y-%m-%d')
|
|
if (now - date).days <= 7:
|
|
lines_new.append(line)
|
|
except Exception:
|
|
# Zeile ohne Datum behalten (zur Sicherheit)
|
|
lines_new.append(line)
|
|
with open(log_path, 'w', encoding='utf-8') as f:
|
|
f.writelines(lines_new)
|
|
with open(log_path, 'a', encoding='utf-8') as f:
|
|
from datetime import datetime as dt
|
|
f.write(f"{dt.now().isoformat()} PAGEVIEW\n")
|
|
tage = werktage = wochentag = datumsrechnung = werktagsrechnung = kw_berechnen = kw_datum = wochen_monate = None
|
|
active_idx = 0
|
|
if request.method == 'POST':
|
|
action = request.form.get('action')
|
|
# Funktions-Logging
|
|
with open(log_path, 'a', encoding='utf-8') as f:
|
|
from datetime import datetime as dt
|
|
f.write(f"{dt.now().isoformat()} FUNC: {action}\n")
|
|
if action == 'tage':
|
|
active_idx = 0
|
|
start = request.form.get('start1')
|
|
end = request.form.get('end1')
|
|
try:
|
|
d1 = datetime.strptime(start, '%Y-%m-%d')
|
|
d2 = datetime.strptime(end, '%Y-%m-%d')
|
|
tage = abs((d2 - d1).days)
|
|
except Exception:
|
|
tage = 'Ungültige Eingabe'
|
|
elif action == 'werktage':
|
|
active_idx = 1
|
|
start = request.form.get('start2')
|
|
end = request.form.get('end2')
|
|
try:
|
|
d1 = datetime.strptime(start, '%Y-%m-%d')
|
|
d2 = datetime.strptime(end, '%Y-%m-%d')
|
|
if d1 > d2:
|
|
d1, d2 = d2, d1
|
|
werktage = np.busday_count(d1.date(), (d2 + timedelta(days=1)).date())
|
|
except Exception:
|
|
werktage = 'Ungültige Eingabe'
|
|
elif action == 'wochentag':
|
|
active_idx = 2
|
|
datum = request.form.get('datum3')
|
|
try:
|
|
d = datetime.strptime(datum, '%Y-%m-%d')
|
|
wochentag = WOCHENTAGE[d.weekday()]
|
|
except Exception:
|
|
wochentag = 'Ungültige Eingabe'
|
|
elif action == 'datumsrechnung':
|
|
active_idx = 3
|
|
datum = request.form.get('datum4')
|
|
tage_input = request.form.get('tage4')
|
|
richtung = request.form.get('richtung4')
|
|
try:
|
|
d = datetime.strptime(datum, '%Y-%m-%d')
|
|
tage_int = int(tage_input)
|
|
if richtung == 'add':
|
|
result = d + timedelta(days=tage_int)
|
|
else:
|
|
result = d - timedelta(days=tage_int)
|
|
datumsrechnung = result.strftime('%d.%m.%Y')
|
|
except Exception:
|
|
datumsrechnung = 'Ungültige Eingabe'
|
|
elif action == 'werktagsrechnung':
|
|
active_idx = 4
|
|
datum = request.form.get('datum5')
|
|
tage_input = request.form.get('tage5')
|
|
richtung = request.form.get('richtung5')
|
|
try:
|
|
d = datetime.strptime(datum, '%Y-%m-%d').date()
|
|
tage_int = int(tage_input)
|
|
if richtung == 'add':
|
|
result = np.busday_offset(d, tage_int, roll='forward')
|
|
else:
|
|
result = np.busday_offset(d, -tage_int, roll='backward')
|
|
werktagsrechnung = np.datetime_as_string(result, unit='D')
|
|
# Formatierung auf deutsch
|
|
dt = datetime.strptime(werktagsrechnung, '%Y-%m-%d')
|
|
werktagsrechnung = dt.strftime('%d.%m.%Y')
|
|
except Exception:
|
|
werktagsrechnung = 'Ungültige Eingabe'
|
|
elif action == 'kw_berechnen':
|
|
active_idx = 5
|
|
datum = request.form.get('datum6')
|
|
try:
|
|
d = datetime.strptime(datum, '%Y-%m-%d')
|
|
kw = d.isocalendar().week
|
|
kw_berechnen = f"KW {kw} ({d.year})"
|
|
except Exception:
|
|
kw_berechnen = 'Ungültige Eingabe'
|
|
elif action == 'kw_datum':
|
|
active_idx = 6
|
|
jahr = request.form.get('jahr7')
|
|
kw = request.form.get('kw7')
|
|
try:
|
|
jahr = int(jahr)
|
|
kw = int(kw)
|
|
# Montag der KW
|
|
start = datetime.fromisocalendar(jahr, kw, 1)
|
|
end = datetime.fromisocalendar(jahr, kw, 7)
|
|
kw_datum = f"{start.strftime('%d.%m.%Y')} bis {end.strftime('%d.%m.%Y')}"
|
|
except Exception:
|
|
kw_datum = 'Ungültige Eingabe'
|
|
elif action == 'wochen_monate':
|
|
datum = request.form.get('datum8')
|
|
anzahl = request.form.get('anzahl8')
|
|
einheit = request.form.get('einheit8')
|
|
richtung = request.form.get('richtung8')
|
|
try:
|
|
d = datetime.strptime(datum, '%Y-%m-%d')
|
|
anzahl_int = int(anzahl)
|
|
if richtung == 'sub':
|
|
anzahl_int = -anzahl_int
|
|
if einheit == 'wochen':
|
|
result = d + timedelta(weeks=anzahl_int)
|
|
else:
|
|
result = d + relativedelta(months=anzahl_int)
|
|
wochen_monate = result.strftime('%d.%m.%Y')
|
|
except Exception:
|
|
wochen_monate = 'Ungültige Eingabe'
|
|
return render_template('index.html', tage=tage, werktage=werktage, wochentag=wochentag, datumsrechnung=datumsrechnung, werktagsrechnung=werktagsrechnung, kw_berechnen=kw_berechnen, kw_datum=kw_datum, active_idx=active_idx, wochen_monate=wochen_monate)
|
|
|
|
|
|
@app.route('/stats', methods=['GET', 'POST'])
|
|
def stats():
|
|
stats_password = os.environ.get('STATS_PASSWORD', 'changeme')
|
|
if 'stats_auth' not in session:
|
|
if request.method == 'POST':
|
|
if request.form.get('password') == stats_password:
|
|
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)
|
|
# Auswertung der Logdatei
|
|
log_path = os.path.join('log', 'pageviews.log')
|
|
pageviews = 0
|
|
func_counts = {}
|
|
impressions_per_day = {}
|
|
if os.path.exists(log_path):
|
|
with open(log_path, encoding='utf-8') as f:
|
|
for line in f:
|
|
if 'PAGEVIEW' in line:
|
|
pageviews += 1
|
|
# Datum extrahieren (YYYY-MM-DD)
|
|
try:
|
|
date = line[:10]
|
|
if len(date) == 10 and date[4] == '-' and date[7] == '-':
|
|
impressions_per_day[date] = impressions_per_day.get(date, 0) + 1
|
|
except Exception:
|
|
pass
|
|
elif 'FUNC:' in line:
|
|
func = line.split('FUNC:')[1].strip()
|
|
func_counts[func] = func_counts.get(func, 0) + 1
|
|
return render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, impressions_per_day=impressions_per_day)
|
|
|
|
|
|
@app.route('/monitor')
|
|
def monitor():
|
|
log_path = os.path.join('log', 'pageviews.log')
|
|
pageviews = 0
|
|
if os.path.exists(log_path):
|
|
with open(log_path, encoding='utf-8') as f:
|
|
for line in f:
|
|
if 'PAGEVIEW' in line:
|
|
pageviews += 1
|
|
uptime = int(time.time() - app_start_time)
|
|
return jsonify({
|
|
"status": "ok",
|
|
"message": "App running",
|
|
"time": datetime.now().isoformat(),
|
|
"uptime_seconds": uptime,
|
|
"pageviews_last_7_days": pageviews
|
|
})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, host="0.0.0.0") |