checklist.py 1.8 KB

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