Skip to content

Commit c140c4e

Browse files
committed
221225
1 parent 4de876a commit c140c4e

2 files changed

Lines changed: 188 additions & 67 deletions

File tree

Lines changed: 79 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,121 @@
11
"""
2-
Flask Web App zur Anzeige aller Daten aus der Tags-Tabelle der momox.db Datenbank
2+
Flask Web App to display all data from the Tags table in the momox.db database.
3+
Optimized version with better error handling and resource management.
34
"""
45

5-
from flask import Flask, render_template
6+
from flask import Flask, render_template, jsonify
67
import sqlite3
78
import os
9+
from contextlib import contextmanager
810

911
app = Flask(__name__)
12+
app.config['JSON_AS_ASCII'] = False # Support for non-ASCII characters in JSON
1013

11-
# Pfad zur Datenbank
14+
# Database path configuration
1215
DB_PATH = os.path.join(os.path.dirname(__file__), 'momox.db')
1316

1417

18+
@contextmanager
1519
def get_db_connection():
16-
"""Erstellt eine Verbindung zur SQLite-Datenbank"""
20+
"""Context manager for database connections to ensure proper resource cleanup."""
1721
conn = sqlite3.connect(DB_PATH)
18-
conn.row_factory = sqlite3.Row # Ermöglicht Zugriff auf Spalten über Namen
19-
return conn
22+
conn.row_factory = sqlite3.Row # Enable column access by name
23+
try:
24+
yield conn
25+
finally:
26+
conn.close()
2027

2128

2229
@app.route('/')
2330
def index():
24-
"""Hauptseite - zeigt alle Tags aus der Datenbank"""
31+
"""Main page - displays all tags from the database in a formatted table."""
2532
try:
26-
conn = get_db_connection()
27-
cursor = conn.cursor()
28-
29-
# Alle Daten aus der Tags-Tabelle abrufen
30-
cursor.execute('SELECT * FROM Tags')
31-
tags = cursor.fetchall()
32-
33-
# Spaltennamen ermitteln
34-
column_names = [description[0] for description in cursor.description]
35-
36-
conn.close()
33+
with get_db_connection() as conn:
34+
cursor = conn.cursor()
35+
cursor.execute('SELECT * FROM Tags')
36+
tags = cursor.fetchall()
37+
column_names = [description[0] for description in cursor.description] if cursor.description else []
3738

3839
return render_template('tags.html', tags=tags, columns=column_names)
3940

4041
except sqlite3.Error as e:
41-
return f"<h1>Datenbankfehler</h1><p>Fehler beim Zugriff auf die Datenbank: {str(e)}</p><p>Stellen Sie sicher, dass die Datei 'momox.db' im gleichen Verzeichnis wie die App existiert.</p>"
42+
error_msg = f"""
43+
<h1>Database Error</h1>
44+
<p>Error accessing the database: {str(e)}</p>
45+
<p>Please ensure that the 'momox.db' file exists in the same directory as the application.</p>
46+
<p><a href="/">Try Again</a></p>
47+
"""
48+
return error_msg, 500
4249
except Exception as e:
43-
return f"<h1>Fehler</h1><p>Ein Fehler ist aufgetreten: {str(e)}</p>"
50+
return f"<h1>Error</h1><p>An unexpected error occurred: {str(e)}</p><p><a href='/'>Return Home</a></p>", 500
4451

4552

46-
@app.route('/raw')
47-
def raw_data():
48-
"""Zeigt die Rohdaten als einfache Liste"""
53+
@app.route('/api/tags')
54+
def api_tags():
55+
"""API endpoint - returns tags data as JSON for programmatic access."""
4956
try:
50-
conn = get_db_connection()
51-
cursor = conn.cursor()
57+
with get_db_connection() as conn:
58+
cursor = conn.cursor()
59+
cursor.execute('SELECT * FROM Tags')
60+
tags = cursor.fetchall()
61+
column_names = [description[0] for description in cursor.description] if cursor.description else []
5262

53-
cursor.execute('SELECT * FROM Tags')
54-
tags = cursor.fetchall()
63+
# Convert rows to dictionaries
64+
tags_list = [dict(zip(column_names, row)) for row in tags]
5565

56-
conn.close()
66+
return jsonify({
67+
'success': True,
68+
'count': len(tags_list),
69+
'columns': column_names,
70+
'data': tags_list
71+
})
72+
73+
except sqlite3.Error as e:
74+
return jsonify({
75+
'success': False,
76+
'error': f'Database error: {str(e)}'
77+
}), 500
78+
79+
80+
@app.route('/raw')
81+
def raw_data():
82+
"""Displays raw data as a simple list."""
83+
try:
84+
with get_db_connection() as conn:
85+
cursor = conn.cursor()
86+
cursor.execute('SELECT * FROM Tags')
87+
tags = cursor.fetchall()
5788

58-
result = "<h1>Tags - Rohdaten</h1>"
59-
result += f"<p>Anzahl der Einträge: {len(tags)}</p>"
60-
result += "<ul>"
89+
result = "<h1>Tags - Raw Data</h1>"
90+
result += f"<p>Number of entries: {len(tags)}</p>"
91+
result += "<ul style='font-family: monospace;'>"
6192
for tag in tags:
6293
result += f"<li>{dict(tag)}</li>"
6394
result += "</ul>"
64-
result += '<br><a href="/">Zurück zur formatierten Ansicht</a>'
95+
result += '<br><a href="/">← Back to formatted view</a> | <a href="/api/tags">View as JSON</a>'
6596

6697
return result
6798

6899
except sqlite3.Error as e:
69-
return f"<h1>Datenbankfehler</h1><p>{str(e)}</p>"
100+
return f"<h1>Database Error</h1><p>{str(e)}</p>", 500
101+
102+
103+
@app.errorhandler(404)
104+
def not_found(error):
105+
"""Custom 404 error handler."""
106+
return "<h1>404 - Page Not Found</h1><p><a href='/'>Return Home</a></p>", 404
70107

71108

72109
if __name__ == '__main__':
73-
# Überprüfen, ob die Datenbank existiert
110+
# Check if database exists on startup
74111
if not os.path.exists(DB_PATH):
75-
print(f"WARNUNG: Die Datenbank '{DB_PATH}' wurde nicht gefunden!")
76-
print("Bitte stellen Sie sicher, dass die Datei 'momox.db' im gleichen Verzeichnis existiert.")
112+
print(f"⚠️ WARNING: Database '{DB_PATH}' not found!")
113+
print("Please ensure that 'momox.db' exists in the same directory.")
114+
else:
115+
print(f"✓ Database found: {DB_PATH}")
116+
117+
print("\n🚀 Starting Flask server...")
118+
print("📍 Access the app at: http://localhost:5000")
119+
print("📊 API endpoint available at: http://localhost:5000/api/tags\n")
77120

78121
app.run(debug=True, host='0.0.0.0', port=5000)

0 commit comments

Comments
 (0)