from flask import Flask, render_template, Blueprint, request, redirect, url_for, current_app from datetime import timezone import json import os clbp = Blueprint('todolist', __name__) def save_todolist(list_items): # Save todolist items new_list = json.dumps(list_items, indent=4) list_file = os.path.join(current_app.instance_path, 'list.py') try: with open(list_file, 'w') as f: f.write(f'LIST = {new_list}') f.close current_app.config.from_pyfile('list.py', silent=True) # Reread the list into the app except Exception as sclerror: current_app.logger.error(f'Couldn\'t save list.py: {sclerror.args[0]}') @clbp.route('/', methods=['GET', 'POST']) def index(): todolist_items = current_app.config['LIST'] if request.method == 'POST': todolist_items = current_app.config['LIST'] item = request.form.get('item') if item: todolist_items.append({'name': item, 'crossed': 'no'}) save_todolist(todolist_items) # Save to file after adding return redirect(url_for('todolist.index')) return render_template('index.html', items=todolist_items) @clbp.route('/cross/') def cross(item_id): todolist_items = current_app.config['LIST'] if 0 <= item_id < len(todolist_items): todolist_items[item_id]['crossed'] = 'yes' save_todolist(todolist_items) # Save to file after crossing return redirect(url_for('todolist.index')) @clbp.route('/uncross/') def uncross(item_id): todolist_items = current_app.config['LIST'] if 0 <= item_id < len(todolist_items): todolist_items[item_id]['crossed'] = 'no' save_todolist(todolist_items) # Save to file after crossing return redirect(url_for('todolist.index')) @clbp.route('/clear') def clear(): todolist_items = current_app.config['LIST'] todolist_items = [] # Clear the list save_todolist(todolist_items) # Save the empty list return redirect(url_for('todolist.index')) @clbp.route('/list') def list(): todolist_items = current_app.config['LIST'] return render_template('list.html', items=todolist_items)