bluenevus commited on
Commit
b438a34
·
verified ·
1 Parent(s): d30d3eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -78
app.py CHANGED
@@ -2,46 +2,22 @@ import dash
2
  from dash import dcc, html, Input, Output, State, callback
3
  import dash_bootstrap_components as dbc
4
  import uuid
5
- import sqlite3
6
  import os
7
 
8
  app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
9
 
10
- DB_FILE = 'links.db'
11
 
12
- def get_db_connection():
13
- conn = sqlite3.connect(DB_FILE, check_same_thread=False)
14
- conn.row_factory = sqlite3.Row
15
- return conn
 
16
 
17
- def init_db():
18
- try:
19
- conn = get_db_connection()
20
- c = conn.cursor()
21
- c.execute('''CREATE TABLE IF NOT EXISTS links
22
- (id TEXT PRIMARY KEY, name TEXT, url TEXT)''')
23
- conn.commit()
24
- print(f"Database initialized successfully at {os.path.abspath(DB_FILE)}")
25
- except Exception as e:
26
- print(f"Error initializing database: {e}")
27
- finally:
28
- conn.close()
29
-
30
- init_db()
31
-
32
- def get_links():
33
- try:
34
- conn = get_db_connection()
35
- c = conn.cursor()
36
- c.execute("SELECT * FROM links")
37
- links = [dict(row) for row in c.fetchall()]
38
- print(f"Retrieved links from database: {links}") # Debug print
39
- return links
40
- except Exception as e:
41
- print(f"Error retrieving links: {e}")
42
- return []
43
- finally:
44
- conn.close()
45
 
46
  def generate_url_list(links):
47
  url_list = [
@@ -64,7 +40,51 @@ def generate_url_list(links):
64
  print(f"Generated URL list: {url_list}") # Debug print
65
  return url_list
66
 
67
- # ... (rest of the layout code remains the same)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  @callback(
70
  [Output('url-list', 'children'),
@@ -87,45 +107,26 @@ def update_url_list(trigger_load, add_clicks, delete_clicks, new_name, new_link)
87
 
88
  feedback = None
89
  status = ''
 
90
 
91
  if triggered_id == 'trigger-load':
92
  print("Initial load triggered")
93
  elif triggered_id == 'add-url-button' and new_name and new_link:
94
- try:
95
- conn = get_db_connection()
96
- c = conn.cursor()
97
- new_id = str(uuid.uuid4())
98
- c.execute("INSERT INTO links VALUES (?, ?, ?)", (new_id, new_name, new_link))
99
- conn.commit()
100
- print(f"Added new URL to database: {new_name}, {new_link}") # Debug print
101
- feedback = html.Div("URL added successfully!", style={'color': 'green'})
102
- status = 'added'
103
- except Exception as e:
104
- print(f"Error adding URL to database: {e}")
105
- feedback = html.Div("Error adding URL. Please try again.", style={'color': 'red'})
106
- status = 'error'
107
- finally:
108
- conn.close()
109
  elif 'delete-button' in triggered_id:
110
  delete_id = eval(triggered_id)['index']
111
- try:
112
- conn = get_db_connection()
113
- c = conn.cursor()
114
- c.execute("DELETE FROM links WHERE id = ?", (delete_id,))
115
- conn.commit()
116
- print(f"Deleted URL with id from database: {delete_id}") # Debug print
117
- feedback = html.Div("URL deleted successfully!", style={'color': 'green'})
118
- status = 'deleted'
119
- except Exception as e:
120
- print(f"Error deleting URL from database: {e}")
121
- feedback = html.Div("Error deleting URL. Please try again.", style={'color': 'red'})
122
- status = 'error'
123
- finally:
124
- conn.close()
125
 
126
- links = get_links()
127
  url_list = generate_url_list(links)
128
-
129
  return url_list, feedback, status
130
 
131
  @callback(
@@ -138,21 +139,15 @@ def update_iframe(n_clicks):
138
  return dash.no_update
139
  button_id = ctx.triggered[0]['prop_id'].split('.')[0]
140
  clicked_id = eval(button_id)['index']
141
- try:
142
- conn = get_db_connection()
143
- c = conn.cursor()
144
- c.execute("SELECT url FROM links WHERE id = ?", (clicked_id,))
145
- result = c.fetchone()
146
- if result:
147
- print(f"Loading URL: {result['url']}") # Debug print
148
- return result['url']
149
- except Exception as e:
150
- print(f"Error loading URL: {e}")
151
- finally:
152
- conn.close() # This line was likely causing the IndentationError
153
  return dash.no_update
154
 
155
  if __name__ == '__main__':
156
  print("Starting the Dash application...")
 
157
  app.run(debug=True, host='0.0.0.0', port=7860)
158
  print("Dash application has finished running.")
 
2
  from dash import dcc, html, Input, Output, State, callback
3
  import dash_bootstrap_components as dbc
4
  import uuid
5
+ import json
6
  import os
7
 
8
  app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
9
 
10
+ DATA_FILE = 'links.json'
11
 
12
+ def load_links():
13
+ if os.path.exists(DATA_FILE):
14
+ with open(DATA_FILE, 'r') as f:
15
+ return json.load(f)
16
+ return []
17
 
18
+ def save_links(links):
19
+ with open(DATA_FILE, 'w') as f:
20
+ json.dump(links, f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def generate_url_list(links):
23
  url_list = [
 
40
  print(f"Generated URL list: {url_list}") # Debug print
41
  return url_list
42
 
43
+ app.layout = dbc.Container([
44
+ dcc.Store(id='add-url-status', data=''),
45
+ dcc.Store(id='trigger-load', data='load'),
46
+ dbc.Modal([
47
+ dbc.ModalHeader("Add New URL"),
48
+ dbc.ModalBody([
49
+ dbc.Input(id='new-url-name', placeholder="URL Name", className="mb-2"),
50
+ dbc.Input(id='new-url-link', placeholder="URL", className="mb-2"),
51
+ html.Div(id='add-url-feedback')
52
+ ]),
53
+ dbc.ModalFooter(
54
+ dbc.Button("Add", id="add-url-button", className="ml-auto")
55
+ ),
56
+ ], id="add-url-modal"),
57
+ dbc.Row([
58
+ dbc.Col([
59
+ html.H2("My URL App", className="mt-3 mb-4"),
60
+ dbc.Button("Add URL", id="open-modal-button", color="primary", className="mb-3"),
61
+ html.Div(id='url-list'),
62
+ ], width=3, className="bg-light p-3"),
63
+ dbc.Col([
64
+ html.Iframe(
65
+ id='content-iframe',
66
+ style={'width': '100%', 'height': '800px'},
67
+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads",
68
+ allow="fullscreen; geolocation; microphone; camera; midi; encrypted-media; autoplay",
69
+ referrerPolicy="no-referrer"
70
+ )
71
+ ], width=9)
72
+ ])
73
+ ], fluid=True)
74
+
75
+ @callback(
76
+ [Output("add-url-modal", "is_open"),
77
+ Output('new-url-name', 'value'),
78
+ Output('new-url-link', 'value')],
79
+ [Input("open-modal-button", "n_clicks"), Input("add-url-button", "n_clicks")],
80
+ [State("add-url-modal", "is_open")],
81
+ )
82
+ def toggle_modal(n1, n2, is_open):
83
+ if n1 or n2:
84
+ if is_open:
85
+ return False, '', ''
86
+ return True, dash.no_update, dash.no_update
87
+ return is_open, dash.no_update, dash.no_update
88
 
89
  @callback(
90
  [Output('url-list', 'children'),
 
107
 
108
  feedback = None
109
  status = ''
110
+ links = load_links()
111
 
112
  if triggered_id == 'trigger-load':
113
  print("Initial load triggered")
114
  elif triggered_id == 'add-url-button' and new_name and new_link:
115
+ new_id = str(uuid.uuid4())
116
+ links.append({'id': new_id, 'name': new_name, 'url': new_link})
117
+ save_links(links)
118
+ print(f"Added new URL: {new_name}, {new_link}") # Debug print
119
+ feedback = html.Div("URL added successfully!", style={'color': 'green'})
120
+ status = 'added'
 
 
 
 
 
 
 
 
 
121
  elif 'delete-button' in triggered_id:
122
  delete_id = eval(triggered_id)['index']
123
+ links = [link for link in links if link['id'] != delete_id]
124
+ save_links(links)
125
+ print(f"Deleted URL with id: {delete_id}") # Debug print
126
+ feedback = html.Div("URL deleted successfully!", style={'color': 'green'})
127
+ status = 'deleted'
 
 
 
 
 
 
 
 
 
128
 
 
129
  url_list = generate_url_list(links)
 
130
  return url_list, feedback, status
131
 
132
  @callback(
 
139
  return dash.no_update
140
  button_id = ctx.triggered[0]['prop_id'].split('.')[0]
141
  clicked_id = eval(button_id)['index']
142
+ links = load_links()
143
+ for link in links:
144
+ if link['id'] == clicked_id:
145
+ print(f"Loading URL: {link['url']}") # Debug print
146
+ return link['url']
 
 
 
 
 
 
 
147
  return dash.no_update
148
 
149
  if __name__ == '__main__':
150
  print("Starting the Dash application...")
151
+ print(f"Data file location: {os.path.abspath(DATA_FILE)}")
152
  app.run(debug=True, host='0.0.0.0', port=7860)
153
  print("Dash application has finished running.")