checklist.py 2.2 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('checklist', __name__)
  6. def save_checklist(list_items): # Save checklist 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. checklist_items = current_app.config['LIST']
  19. if request.method == 'POST':
  20. checklist_items = current_app.config['LIST']
  21. item = request.form.get('item')
  22. if item:
  23. checklist_items.append({'name': item, 'checked': 'no'})
  24. save_checklist(checklist_items) # Save to file after adding
  25. return redirect(url_for('checklist.index'))
  26. return render_template('index.html', items=checklist_items)
  27. @clbp.route('/check/<int:item_id>')
  28. def check(item_id):
  29. checklist_items = current_app.config['LIST']
  30. if 0 <= item_id < len(checklist_items):
  31. checklist_items[item_id]['checked'] = 'yes'
  32. save_checklist(checklist_items) # Save to file after checking
  33. return redirect(url_for('checklist.index'))
  34. @clbp.route('/uncheck/<int:item_id>')
  35. def uncheck(item_id):
  36. checklist_items = current_app.config['LIST']
  37. if 0 <= item_id < len(checklist_items):
  38. checklist_items[item_id]['checked'] = 'no'
  39. save_checklist(checklist_items) # Save to file after checking
  40. return redirect(url_for('checklist.index'))
  41. @clbp.route('/clear')
  42. def clear():
  43. checklist_items = current_app.config['LIST']
  44. checklist_items = [] # Clear the list
  45. save_checklist(checklist_items) # Save the empty list
  46. return redirect(url_for('checklist.index'))
  47. @clbp.route('/list')
  48. def list():
  49. checklist_items = current_app.config['LIST']
  50. return render_template('list.html', items=checklist_items)