No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

67 líneas
2.1KB

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