from wtforms import SubmitField, StringField, HiddenField, validators, Form from flask_wtf import FlaskForm from flask import request, render_template, redirect from flask_login import login_required, current_user from main import db, app, ma from sqlalchemy import Sequence from sqlalchemy.exc import SQLAlchemyError from status import st, Status ################################################################################ # Class describing Author in the database, and via sqlalchemy, connected to the DB as well ################################################################################ class Author(db.Model): id = db.Column(db.Integer, db.Sequence('author_id_seq'), primary_key=True ) surname = db.Column(db.String(30), unique=False, nullable=False) firstnames = db.Column(db.String(50), unique=False, nullable=False) def __repr__(self): return f"" ################################################################################ # Helper class that inherits a .dump() method to turn class Author into json / useful in jinja2 ################################################################################ class AuthorSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Author ordered = True ################################################################################ # Helper class that defines a form for author, used to make html
, with field validation (via wtforms) ################################################################################ class AuthorForm(FlaskForm): id = HiddenField() firstnames = StringField('FirstName(s):', [validators.DataRequired()]) surname = StringField('Surname:', [validators.DataRequired()]) submit = SubmitField('Save' ) delete = SubmitField('Delete' ) ################################################################################ # Routes for author data # # /authors -> GET only -> prints out list of all authors ################################################################################ @app.route("/authors", methods=["GET"]) @login_required def authors(): authors = Author.query.order_by(Author.surname, Author.firstnames).all() return render_template("authors.html", authors=authors, alert=st.GetAlert(), message=st.GetMessage() ) ################################################################################ # /author -> GET/POST -> creates a new author type and when created, takes you back to /authors ################################################################################ @app.route("/author", methods=["GET", "POST"]) @login_required def new_author(): form = AuthorForm(request.form) page_title='Create new Author' if 'surname' not in request.form: return render_template("edit_id_name.html", form=form, page_title=page_title ) else: author = Author( surname=request.form["surname"], firstnames=request.form["firstnames"] ) try: db.session.add(author) db.session.commit() st.SetMessage( f"Created new Author ({author.surname}, {author.firstnames})" ) return redirect( '/authors' ) except SQLAlchemyError as e: st.SetAlert( "danger" ) st.SetMessage( f"Failed to add Author: {e.orig}" ) return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() ) ################################################################################ # /author/ -> GET/POST(save or delete) -> shows/edits/delets a single author ################################################################################ @app.route("/author/", methods=["GET", "POST"]) @login_required def author(id): ### DDP: should this be request.form or request.values? form = AuthorForm(request.form) page_title='Edit Author' if request.method == 'POST' and form.validate(): try: author = Author.query.get(id) if 'delete' in request.form: st.SetMessage( f"Successfully deleted Author: ({author.surname}, {author.firstnames})" ) author = Author.query.filter(Author.id==id).delete() if 'submit' in request.form: st.SetMessage( f"Successfully Updated Author: (From: {author.surname}, {author.firstnames}" ) author.surname = request.form['surname'] author.firstnames = request.form['firstnames'] st.AppendMessage( f" To: {author.surname}, {author.firstnames})" ) db.session.commit() return redirect( '/authors' ) except SQLAlchemyError as e: st.SetAlert( "danger" ) st.SetMessage( f"Failed to modify Author: {e.orig}" ) return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() ) else: print(id) author = Author.query.get(id) form = AuthorForm(request.values, obj=author) return render_template("edit_id_name.html", object=author, form=form, page_title = page_title, alert=st.GetAlert(), message=st.GetMessage() ) @app.route("/author//books", methods=["GET"]) @login_required def authors_books(author_id): """ show all the books written by the specified author """ from main import Book, Book_Author_Link books=Book.query.join(Book_Author_Link).join(Author).filter(Author.id==author_id).order_by(Book.title).all() # now need to re-order books to cater for sub-book ordering ordered_books=[] processed=[] for b in books: if b.id not in processed: if b.IsParent(): ordered_books.append(b) processed.append( b.id ) for bb in b.child_ref: tmp=Book.query.get(bb.sub_book_id) ordered_books.append( tmp ) processed.append( bb.sub_book_id ) elif b.IsChild(): ordered_books.append(b.parent) processed.append( b.parent.id ) cnt=1 for bb in b.parent.child_ref: tmp=Book.query.get(bb.sub_book_id) # need to set parent_id and sub_book_num for indenting to work in html tmp.parent_id=b.parent.id tmp.sub_book_num=cnt ordered_books.append( tmp ) processed.append( bb.sub_book_id ) cnt+=1 else: ordered_books.append(b) processed.append( b.id ) a=Author.query.get(author_id) return render_template("books.html", books=ordered_books, page_title=f"All {a.surname}, {a.firstnames} books:", no_navbar=True ) ################################################################################ # helper fund to GetAuthors -> author_list -> jinja2 for author drop-down in book.html ################################################################################ def GetAuthors(): return Author.query.order_by('surname','firstnames').all()