from flask import Flask from flask import render_template from flask import request from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow DB_URL = 'postgresql+psycopg2://ddp:NWNlfa01@127.0.0.1:5432/library' app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ma = Marshmallow(app) ####################################### CLASSES / DB model ####################################### book_author_link = db.Table('book_author_link', db.Model.metadata, db.Column('book_id', db.Integer, db.ForeignKey('book.id')), db.Column('author_id', db.Integer, db.ForeignKey('author.id')) ) book_publisher_link = db.Table('book_publisher_link', db.Model.metadata, db.Column('book_id', db.Integer, db.ForeignKey('book.id')), db.Column('publisher_id', db.Integer, db.ForeignKey('publisher.id')) ) book_genre_link = db.Table('book_genre_link', db.Model.metadata, db.Column('book_id', db.Integer, db.ForeignKey('book.id')), db.Column('genre_id', db.Integer, db.ForeignKey('genre_lst.id')) ) class Book_Sub_Book_Link(db.Model): __tablename__ = "book_sub_book_link" book_id = db.Column(db.Integer, db.ForeignKey('book.id'), unique=True, nullable=False, primary_key=True) sub_book_id = db.Column(db.Integer, db.ForeignKey('book.id'), unique=True, nullable=False, primary_key=True) sub_book_num = db.Column(db.Integer) def __repr__(self): return "".format(self.id, self.author, self.title, self.year_published, self.rating, self.condition, self.owned, self.covertype, self.notes, self.blurb, self.created, self.modified, self.publisher ) class Author(db.Model): id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) firstnames = db.Column(db.String(50), unique=False, nullable=False) surname = db.Column(db.String(30), unique=False, nullable=False) def __repr__(self): return "".format(self.id,self.firstnames, self.surname) class Publisher(db.Model): id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) name = db.Column(db.String(50), unique=False, nullable=False) def __repr__(self): return "".format(self.id, self.name) class Genre_Lst(db.Model): __tablename__ = "genre_lst" id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) genre = db.Column(db.String(20), unique=False, nullable=False) def __repr__(self): return "".format(self.id, self.genre) ### setup serializer schemas, to make returning books/authors easier class AuthorSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Author include_relationships = True load_instance = True class PublisherSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Publisher include_relationships = True load_instance = True class Genre_LstSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Genre_Lst include_relationships = True load_instance = True class Book_Sub_Book_LinkSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Book_Sub_Book_Link include_relationships = True load_instance = True class BookSchema(ma.SQLAlchemyAutoSchema): author = ma.Nested(AuthorSchema, many=True) publisher = ma.Nested(PublisherSchema, many=True) genre = ma.Nested(Genre_LstSchema, many=True) parent_ref = ma.Nested(Book_Sub_Book_LinkSchema, many=True) child_ref = ma.Nested(Book_Sub_Book_LinkSchema, many=True) class Meta: model = Book include_relationships = True load_instance = True ### DDP: do I need many=True on Author as books have many authors? (or in BookSchema declaration above?) book_schema = BookSchema() ####################################### ROUTES ####################################### @app.route("/books", methods=["GET"]) def books(): if request.form: print(request.form) ### DDP: this fails... also, maybe we use ORM to build a parent_book (and I am child #4) and child_books??? # books = Book.query.all() books = Book.query.outerjoin(Book_Sub_Book_Link, Book.id==Book_Sub_Book_Link.book_id).order_by(Book.id, Book_Sub_Book_Link.sub_book_num).all() # want to get sub book info and patch it into the books object to at least reference sub_book_num and parent_book, # then per book in jinja2, slide it into the right aprt of the table with the right markup to show its a sub book subs = db.engine.execute ( "select * from book_sub_book_link" ) for row in subs: index = next((i for i, item in enumerate(books) if item.id == row.sub_book_id), -1) books[index].parent_id = row.book_id books[index].sub_book_num = row.sub_book_num return render_template("books.html", books=books) @app.route("/book/", methods=["GET"]) def book(id): book = Book.query.get(id) book_s = book_schema.dump(book) # force sub books for jinja2 to be able to use subs = db.engine.execute ( "select bsb.book_id, bsb.sub_book_id, bsb.sub_book_num, book.title, book.rating, book.year_published, book.notes, bal.author_id as author_id, author.surname||', '||author.firstnames as author from book_sub_book_link bsb, book, book_author_link bal, author where bsb.book_id = {} and book.id = bsb.sub_book_id and book.id = bal.book_id and bal.author_id = author.id".format( id ) ) sub_book=[] for row in subs: # get genres for sub book and add by hand first tmp_g = [] genres = db.engine.execute ( "select genre_lst.id, genre_lst.genre from genre_lst, book_genre_link bgl where genre_lst.id = bgl.genre_id and bgl.book_id = {}".format( row.sub_book_id ) ) for genre in genres: tmp_g.append( { 'id': genre.id, 'genre': genre.genre } ) sub_book.append( { 'sub_book_id': row.sub_book_id, 'sub_book_num': row.sub_book_num, 'title' : row.title, 'rating': row.rating, 'year_published' : row.year_published, 'notes' : row.notes, 'author_id' : row.author_id, 'author' : row.author, 'genres' : tmp_g } ) book_s['sub_book'] = sub_book print( "parent book details:" ) print( book.parent_ref ) print( "child book details:" ) print( book.child_ref ) return render_template("books.html", books=book_s, subs=sub_book ) @app.route("/authors", methods=["GET"]) def author(): authors = Author.query.all() return render_template("author.html", authors=authors) if __name__ == "__main__": app.run(host="0.0.0.0", debug=True)