選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

68 行
2.3KB

  1. # @name: example.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: example route for example-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 Example
  12. from werkzeug.exceptions import abort
  13. from . import db
  14. example = Blueprint('example', __name__)
  15. # function to retrieve data about a single example from the database
  16. def get_example(example_id):
  17. example = Example.query.filter_by(id=example_id).first()
  18. if example is None:
  19. abort(404)
  20. return example
  21. # route for displaying all examples in database
  22. @example.route('/examples')
  23. def get_examples():
  24. examples = Example.query
  25. return render_template('examples.html', examples=examples)
  26. # route for displaying a single example based on the ID in the database
  27. @example.route('/examples/<int:example_id>')
  28. def show_example(example_id):
  29. example = get_example(example_id)
  30. return render_template('example.html', example=example)
  31. # route for editing a single example based on the ID in the database
  32. @example.route('/examples/<int:example_id>/edit', methods=('GET', 'POST'))
  33. @login_required
  34. def edit_example(example_id):
  35. example = get_example(example_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. example = Example.query.get(example_id)
  43. example.name = name
  44. example.description = description
  45. db.session.commit()
  46. return redirect(url_for('example.get_examples'))
  47. return render_template('edit.html', example=example)
  48. # route for function to delete a single example from the edit page
  49. @example.route('/examples/<int:example_id>/delete', methods=('POST',))
  50. @login_required
  51. def delete_example(example_id):
  52. example = get_example(example_id)
  53. deletion = Example.query.get(example_id)
  54. db.session.delete(deletion)
  55. db.session.commit()
  56. flash('Successfully deleted!')
  57. return redirect(url_for('example.get_examples'))