-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
264 lines (212 loc) · 9.48 KB
/
main.py
File metadata and controls
264 lines (212 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from flask import Flask, render_template, request, redirect, url_for, flash, session, g
from waitress import serve
from flask_sqlalchemy import SQLAlchemy
import uuid
import logging
from functools import wraps
import json
from sqlalchemy import or_
import re
from users import USERS
# Configure logging
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
app.secret_key = 'super_secret_key_change_me'
# --- Database Configuration ---
# Configure SQLite database URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# --- Database Model ---
class Task(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
title = db.Column(db.String(100), nullable=False, default='Untitled Task')
text = db.Column(db.Text, nullable=False)
table_data = db.Column(db.Text, nullable=False, default='[]')
status = db.Column(db.String(20), nullable=False, default='start')
def __repr__(self):
return f"Task('{self.title}', '{self.status}')"
# --- Database Initialization Command ---
import click
@app.cli.command('init-db')
def init_db_command():
with app.app_context():
db.drop_all()
db.create_all()
click.echo('Initialized the database.')
def login_required(view):
@wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
flash('Login required to access this page.', 'warning')
return redirect(url_for('login', next=request.url))
return view(**kwargs)
return wrapped_view
@app.before_request
def load_logged_in_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
g.user = user_id
# --- End Authentication Setup ---
@app.route('/')
def index():
search_query = request.args.get('search')
query = Task.query
if search_query:
query = query.filter(or_(
Task.title.ilike(f'%{search_query}%'),
Task.text.ilike(f'%{search_query}%')
))
logging.debug("Filtering tasks with search query: '%s'", search_query)
# --- Sorting
non_done_tasks = query.filter(Task.status != 'done').order_by(Task.title).all()
done_tasks = query.filter(Task.status == 'done').order_by(Task.title).all()
tasks = non_done_tasks + done_tasks
# ------
logging.debug("Rendering index page with %d tasks (after search/sort). User: %s", len(tasks), g.user)
return render_template('index.html', tasks=tasks, search_query=search_query)
@app.route('/create', methods=['GET', 'POST'])
@login_required
def create_task():
"""Handle task creation."""
if request.method == 'POST':
logging.debug("Received POST request for task creation by user: %s", g.user)
title = request.form.get('title', 'Untitled Task')
text = request.form.get('text', '')
table_data_list = []
row_data_dict = {}
input_name_pattern = re.compile(r'col_(\d+)_row_(\d+)')
for key, value in request.form.items():
match = input_name_pattern.match(key)
if match:
col_index = int(match.group(1))
row_index = int(match.group(2))
if row_index not in row_data_dict:
row_data_dict[row_index] = ['', '', '', '']
if 0 <= col_index < 4:
row_data_dict[row_index][col_index] = value or ''
updated_table_data_list = [row_data_dict[i] for i in sorted(row_data_dict.keys())]
table_data_json = json.dumps(updated_table_data_list)
new_task = Task(
title=title,
text=text,
table_data=table_data_json,
status='start'
)
db.session.add(new_task)
db.session.commit()
logging.debug("Created task with ID: %s and title: %s by user: %s", new_task.id, new_task.title, g.user)
flash(f'Task "{new_task.title}" created successfully!', 'success')
return redirect(url_for('view_task', task_id=new_task.id))
logging.debug("Rendering create_task page for user: %s", g.user)
return render_template('create_task.html')
@app.route('/task/<string:task_id>')
def view_task(task_id):
logging.debug("Attempting to view task with ID: %s by user: %s", task_id, g.user)
task = Task.query.get(task_id)
if task is None:
logging.warning("Task with ID %s not found for user: %s", task_id, g.user)
flash(f'Task with ID {task_id} not found.', 'danger')
return redirect(url_for('index'))
task.table_data_list = json.loads(task.table_data)
logging.debug("Rendering view_task page for task ID: %s for user: %s", task_id, g.user)
return render_template('view_task.html', task=task, user=g.user)
@app.route('/task/<string:task_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_task(task_id):
logging.debug("Attempting to edit task with ID: %s by user: %s", task_id, g.user)
task = Task.query.get(task_id)
if task is None:
logging.warning("Task with ID %s not found for editing by user: %s", task_id, g.user)
flash(f'Task with ID {task_id} not found.', 'danger')
return redirect(url_for('index'))
if request.method == 'POST':
logging.debug("Received POST request for editing task ID: %s by user: %s", task_id, g.user)
# --- Debugging
logging.debug("Raw form data received: %s", request.form)
# ------
task.title = request.form.get('title', 'Untitled Task')
task.text = request.form.get('text', '')
task.status = request.form.get('status', 'start')
row_data_dict = {}
input_name_pattern = re.compile(r'col_(\d+)_row_(\d+)')
for key, value in request.form.items():
match = input_name_pattern.match(key)
if match:
col_index = int(match.group(1))
row_index = int(match.group(2))
# Ensure the row index exists in the dictionary
if row_index not in row_data_dict:
# Initialize row with empty strings for 4 columns
row_data_dict[row_index] = ['', '', '', '']
if 0 <= col_index < 4:
row_data_dict[row_index][col_index] = value or ''
# Convert the dictionary to a sorted list of lists
updated_table_data_list = [row_data_dict[i] for i in sorted(row_data_dict.keys())]
# --- Debugging---
logging.debug("Parsed table data list: %s", updated_table_data_list)
# ------
task.table_data = json.dumps(updated_table_data_list)
db.session.commit()
logging.debug("Updated task ID: %s by user: %s", task_id, g.user)
flash(f'Task "{task.title}" updated successfully!', 'success')
return redirect(url_for('view_task', task_id=task.id))
task.table_data_list = json.loads(task.table_data)
logging.debug("Rendering edit_task page for task ID: %s for user: %s", task_id, g.user)
return render_template('edit_task.html', task=task)
@app.route('/task/<string:task_id>/delete', methods=['POST'])
@login_required
def delete_task(task_id):
logging.debug("Attempting to delete task with ID: %s by user: %s", task_id, g.user)
task = Task.query.get(task_id)
if task:
title = task.title
db.session.delete(task)
db.session.commit()
logging.debug("Deleted task ID: %s by user: %s", task_id, g.user)
flash(f'Task "{title}" deleted successfully!', 'success')
else:
logging.warning("Task with ID %s not found for deletion by user: %s", task_id, g.user)
flash(f'Task with ID {task_id} not found.', 'danger')
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.user is not None:
return redirect(url_for('index'))
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
error = None
if username not in USERS:
error = 'Incorrect username.'
elif USERS[username] != password:
error = 'Incorrect password.'
if error is None:
session.clear()
session['user_id'] = username
logging.info("User '%s' logged in successfully", username)
flash(f'Welcome, {username}!', 'success')
next_page = request.args.get('next') or url_for('index')
return redirect(next_page)
logging.warning("Login failed for user '%s': %s", username, error)
flash(error, 'danger')
logging.debug("Rendering login page")
return render_template('login.html')
@app.route('/logout')
def logout():
"""Handle user logout."""
logging.info("User '%s' logging out", g.user)
session.clear()
flash('You have been logged out.', 'info')
return redirect(url_for('index'))
if __name__ == '__main__':
with app.app_context():
# You might want to run init-db here if you want the db to be
# created automatically on first run, but the CLI command is safer.
# db.create_all()
pass # Use the CLI command 'flask --app app init-db' instead
logging.info("Starting Flask application...")
#app.run(debug=True)
serve(app, host='0.0.0.0', port=9000)