todolist.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from flask import Flask, render_template, Blueprint, request, redirect, url_for, current_app
  2. from datetime import timezone
  3. import json
  4. import os
  5. clbp = Blueprint('todolist', __name__)
  6. def save_todolist(list_items): # Save todolist items
  7. new_list = json.dumps(list_items, indent=4)
  8. list_file = os.path.join(current_app.instance_path, 'list.py')
  9. try:
  10. with open(list_file, 'w') as f:
  11. f.write(f'LIST = {new_list}')
  12. f.close
  13. current_app.config.from_pyfile('list.py', silent=True) # Reread the list into the app
  14. except Exception as sclerror:
  15. current_app.logger.error(f'Couldn\'t save list.py: {sclerror.args[0]}')
  16. @clbp.route('/', methods=['GET', 'POST'])
  17. def index():
  18. todolist_items = current_app.config['LIST']
  19. if request.method == 'POST':
  20. todolist_items = current_app.config['LIST']
  21. item = request.form.get('item')
  22. if item:
  23. todolist_items.append({'name': item, 'crossed': 'no'})
  24. save_todolist(todolist_items) # Save to file after adding
  25. return redirect(url_for('todolist.index'))
  26. return render_template('index.html', items=todolist_items)
  27. @clbp.route('/cross/<int:item_id>')
  28. def cross(item_id):
  29. todolist_items = current_app.config['LIST']
  30. if 0 <= item_id < len(todolist_items):
  31. todolist_items[item_id]['crossed'] = 'yes'
  32. save_todolist(todolist_items) # Save to file after crossing
  33. return redirect(url_for('todolist.index'))
  34. @clbp.route('/uncross/<int:item_id>')
  35. def uncross(item_id):
  36. todolist_items = current_app.config['LIST']
  37. if 0 <= item_id < len(todolist_items):
  38. todolist_items[item_id]['crossed'] = 'no'
  39. save_todolist(todolist_items) # Save to file after crossing
  40. return redirect(url_for('todolist.index'))
  41. @clbp.route('/clear')
  42. def clear():
  43. todolist_items = current_app.config['LIST']
  44. todolist_items = [] # Clear the list
  45. save_todolist(todolist_items) # Save the empty list
  46. return redirect(url_for('todolist.index'))
  47. @clbp.route('/list')
  48. def list():
  49. todolist_items = current_app.config['LIST']
  50. return render_template('list.html', items=todolist_items)