todoaplikacja/mainnowe.py
2024-06-23 18:02:22 +02:00

96 lines
2.4 KiB
Python

from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
def initialize_database():
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tasks
(id INTEGER PRIMARY KEY AUTOINCREMENT,
task TEXT NOT NULL,
completed INTEGER DEFAULT 0)''')
conn.commit()
conn.close()
def add_task(task):
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("INSERT INTO tasks (task) VALUES (?)", (task,))
conn.commit()
conn.close()
def delete_task(task_id):
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("DELETE FROM tasks WHERE id=?", (task_id,))
conn.commit()
conn.close()
def view_tasks():
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("SELECT * FROM tasks WHERE completed=0")
tasks = c.fetchall()
conn.close()
tasks.sort(key=lambda task: task[1])
return tasks
def view_tasks_complited():
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("SELECT * FROM tasks WHERE completed=1")
tasks = c.fetchall()
conn.close()
return tasks
def update_task(task_id, task=None):
conn = sqlite3.connect('todo.db')
c = conn.cursor()
if task:
c.execute("UPDATE tasks SET task=? WHERE id=?", (task, task_id))
conn.commit()
conn.close()
def complete_task(task_id):
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute("UPDATE tasks SET completed=? WHERE id=?", (1, task_id))
conn.commit()
conn.close()
initialize_database()
@app.route('/')
def index():
tasks = view_tasks()
completed_tasks = view_tasks_complited()
return render_template('index.html', tasks=tasks, completed_tasks=completed_tasks)
@app.route('/add', methods=['POST'])
def add():
task = request.form['task']
add_task(task)
return redirect(url_for('index'))
@app.route('/update/<int:task_id>', methods=['POST'])
def update(task_id):
task = request.form['task']
update_task(task_id, task)
return redirect(url_for('index'))
@app.route('/delete/<int:task_id>', methods=['POST'])
def delete(task_id):
delete_task(task_id)
return redirect(url_for('index'))
@app.route('/complete/<int:task_id>', methods=['POST'])
def complete(task_id):
complete_task(task_id)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)