Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

68 linhas
2.4KB

  1. # @name: practice.py
  2. # @version: 0.1
  3. # @creation_date: 2021-11-03
  4. # @license: The MIT License <https://opensource.org/licenses/MIT>
  5. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  6. # @purpose: practice route for practice-related functions and pages
  7. # @acknowledgements:
  8. # https://www.digitalocean.com/community/tutorials/how-to-make-a-web-application-using-flask-in-python-3
  9. from flask import Blueprint, render_template, request, flash, redirect, url_for
  10. from flask_login import login_required, current_user
  11. from .models import Practice
  12. from werkzeug.exceptions import abort
  13. from . import db
  14. practice = Blueprint('practice', __name__)
  15. # function to retrieve data about a single practice from the database
  16. def get_practice(practice_id):
  17. practice = Practice.query.filter_by(id=practice_id).first()
  18. if practice is None:
  19. abort(404)
  20. return practice
  21. # route for displaying all practices in database
  22. @practice.route('/practices')
  23. def get_practices():
  24. practices = Practice.query
  25. return render_template('practices.html', practices=practices)
  26. # route for displaying a single practice based on the ID in the database
  27. @practice.route('/practices/<int:practice_id>')
  28. def show_practice(practice_id):
  29. practice = get_practice(practice_id)
  30. return render_template('practice.html', practice=practice)
  31. # route for editing a single practice based on the ID in the database
  32. @practice.route('/practices/<int:practice_id>/edit', methods=('GET', 'POST'))
  33. @login_required
  34. def edit_practice(practice_id):
  35. practice = get_practice(practice_id)
  36. if request.method == 'POST':
  37. name = request.form['name']
  38. description = request.form['description']
  39. if not name:
  40. flash('Name is required!')
  41. else:
  42. practice = Practice.query.get(practice_id)
  43. practice.name = name
  44. practice.description = description
  45. db.session.commit()
  46. return redirect(url_for('practice.get_practices'))
  47. return render_template('edit.html', practice=practice)
  48. # route for function to delete a single practice from the edit page
  49. @practice.route('/practices/<int:practice_id>/delete', methods=('POST',))
  50. @login_required
  51. def delete_practice(practice_id):
  52. practice = get_practice(practice_id)
  53. deletion = Practice.query.get(practice_id)
  54. db.session.delete(deletion)
  55. db.session.commit()
  56. flash('Successfully deleted!')
  57. return redirect(url_for('practice.get_practices'))