|
1 | 1 | """ |
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. |
3 | 4 | """ |
4 | 5 |
|
5 | | -from flask import Flask, render_template |
| 6 | +from flask import Flask, render_template, jsonify |
6 | 7 | import sqlite3 |
7 | 8 | import os |
| 9 | +from contextlib import contextmanager |
8 | 10 |
|
9 | 11 | app = Flask(__name__) |
| 12 | +app.config['JSON_AS_ASCII'] = False # Support for non-ASCII characters in JSON |
10 | 13 |
|
11 | | -# Pfad zur Datenbank |
| 14 | +# Database path configuration |
12 | 15 | DB_PATH = os.path.join(os.path.dirname(__file__), 'momox.db') |
13 | 16 |
|
14 | 17 |
|
| 18 | +@contextmanager |
15 | 19 | def get_db_connection(): |
16 | | - """Erstellt eine Verbindung zur SQLite-Datenbank""" |
| 20 | + """Context manager for database connections to ensure proper resource cleanup.""" |
17 | 21 | 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() |
20 | 27 |
|
21 | 28 |
|
22 | 29 | @app.route('/') |
23 | 30 | def index(): |
24 | | - """Hauptseite - zeigt alle Tags aus der Datenbank""" |
| 31 | + """Main page - displays all tags from the database in a formatted table.""" |
25 | 32 | 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 [] |
37 | 38 |
|
38 | 39 | return render_template('tags.html', tags=tags, columns=column_names) |
39 | 40 |
|
40 | 41 | 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 |
42 | 49 | 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 |
44 | 51 |
|
45 | 52 |
|
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.""" |
49 | 56 | 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 [] |
52 | 62 |
|
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] |
55 | 65 |
|
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() |
57 | 88 |
|
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;'>" |
61 | 92 | for tag in tags: |
62 | 93 | result += f"<li>{dict(tag)}</li>" |
63 | 94 | 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>' |
65 | 96 |
|
66 | 97 | return result |
67 | 98 |
|
68 | 99 | 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 |
70 | 107 |
|
71 | 108 |
|
72 | 109 | if __name__ == '__main__': |
73 | | - # Überprüfen, ob die Datenbank existiert |
| 110 | + # Check if database exists on startup |
74 | 111 | 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") |
77 | 120 |
|
78 | 121 | app.run(debug=True, host='0.0.0.0', port=5000) |
0 commit comments