removed all refs to genre_lst, made genre table confirm to id, name, added classes/routes for genre*, tweaked book format to accommodate multiple authors, etc. still 1-line, but with 12 / num of <authors, etc.> col wide form-controls

This commit is contained in:
2020-11-15 14:16:58 +11:00
parent 7334e4b622
commit e39a4da6a2
6 changed files with 119 additions and 20 deletions

6
README
View File

@@ -13,6 +13,12 @@ sudo apt install python3-pip python3-psycopg2 libpq-dev
# --user sticks python libs in ~/.local/[bin|lib|share]
pip3 install --user flask sqlalchemy flask-sqlalchemy flask-marshmallow SQLAlchemy-serializer flask-wtf flask-bootstrap marshmallow-sqlalchemy
### alter db that was saved by:
psql library
alter table genre_lst rename to genre;
alter table genre rename COLUMN genre to name;
# run the web server by:
python3 main.py

64
genre.py Normal file
View File

@@ -0,0 +1,64 @@
from wtforms import SubmitField, StringField, HiddenField, validators, Form
from flask import request, render_template
from __main__ import db, app, ma
################################################################################
# Class describing Genre in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Genre(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 "<id: {}, name: {}>".format(self.id,self.name)
################################################################################
# Helper class that inherits a .dump() method to turn class Genre into json / useful in jinja2
################################################################################
class GenreSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Genre
################################################################################
# Helper class that defines a form for genre, used to make html <form>, with field validation (via wtforms)
################################################################################
class GenreForm(Form):
id = HiddenField()
name = StringField('Name:', [validators.DataRequired()])
submit = SubmitField('Save' )
delete = SubmitField('Delete' )
################################################################################
# Routes for genre data
#
# /genres -> GET only -> prints out list of all genres
################################################################################
@app.route("/genres", methods=["GET"])
def genres():
genres = Genre.query.all()
return render_template("genres.html", genres=genres)
################################################################################
# /genre/<id> -> GET/POST(save or delete) -> shows/edits/delets a single genre
################################################################################
@app.route("/genre/<id>", methods=["GET", "POST"])
def genre(id):
### DDP: should this be request.form or request.values?
alert="Success"
genre_form = GenreForm(request.form)
if request.method == 'POST' and genre_form.validate():
id = request.form['id']
genre = Genre.query.get(id)
try:
request.form['submit']
except:
message="Sorry, Deleting unsupported at present"
alert="Danger"
else:
genre.name = request.form['name']
db.session.commit()
message="Successfully Updated Genre (id={})".format(id)
else:
genre = Genre.query.get(id)
genre_form = GenreForm(request.values, obj=genre)
message=""
return render_template("genre.html", genre=genre, alert=alert, message=message, genre_form=genre_form)

22
main.py
View File

@@ -17,6 +17,7 @@ Bootstrap(app)
from author import Author, AuthorForm, AuthorSchema
from publisher import Publisher, PublisherForm, PublisherSchema
from genre import Genre, GenreForm, GenreSchema
####################################### CLASSES / DB model #######################################
book_author_link = db.Table('book_author_link', db.Model.metadata,
@@ -31,7 +32,7 @@ book_publisher_link = db.Table('book_publisher_link', db.Model.metadata,
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'))
db.Column('genre_id', db.Integer, db.ForeignKey('genre.id'))
)
class Book_Sub_Book_Link(db.Model):
@@ -58,31 +59,20 @@ class Book(db.Model):
author = db.relationship('Author', secondary=book_author_link)
publisher = db.relationship('Publisher', secondary=book_publisher_link)
genre = db.relationship('Genre_Lst', secondary=book_genre_link )
genre = db.relationship('Genre', secondary=book_genre_link )
parent_ref = db.relationship('Book_Sub_Book_Link', secondary=Book_Sub_Book_Link.__table__, primaryjoin="Book.id==Book_Sub_Book_Link.sub_book_id", secondaryjoin="Book.id==Book_Sub_Book_Link.book_id" )
child_ref = db.relationship('Book_Sub_Book_Link', secondary=Book_Sub_Book_Link.__table__, primaryjoin="Book.id==Book_Sub_Book_Link.book_id", secondaryjoin="Book.id==Book_Sub_Book_Link.sub_book_id" )
def __repr__(self):
return "<id: {}, author: {}, title: {}, year_published: {}, rating: {}, condition: {}, owned: {}, covertype: {}, notes: {}, blurb: {}, created: {}, modified: {}, publisher: {}>".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 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 "<id: {}, genre: {}>".format(self.id, self.genre)
class Genre_LstSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Genre_Lst
class Book_Sub_Book_LinkSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Book_Sub_Book_Link
class BookSchema(ma.SQLAlchemyAutoSchema):
author = ma.Nested(AuthorSchema, many=True)
publisher = ma.Nested(PublisherSchema, many=True)
genre = ma.Nested(Genre_LstSchema, many=True)
genre = ma.Nested(GenreSchema, 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
@@ -122,9 +112,9 @@ def book(id):
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 ) )
genres = db.engine.execute ( "select genre.id, genre.name from genre, book_genre_link bgl where genre.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 } )
tmp_g.append( { 'id': genre.id, 'name': genre.name } )
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 } )

View File

@@ -9,12 +9,12 @@
<div class="input-group input-group-lg">
<label for="{{key}}" class="col-lg-2 col-form-label">{{key}}:</label>
<div class="col-lg-10">
<div class="row">
{% if books[key] is iterable and books[key] is not string %}
{% set cnt = namespace(idx=0, val=0) %}
{% for objects in books[key] %}
{% set cnt.val = 0 %}
{% set str = namespace(val="") %}
<span class="form-control-plaintext" id="{{key}}">
{% for attr in objects %}
{% if attr != "id" %}
{% if cnt.val > 0 %}
@@ -25,12 +25,12 @@
{% set cnt.val = cnt.val + 1 %}
{% endif %}
{% endfor %}
{% if key != "genre" %}
<a href="{{url_for(key, id=books[key][cnt.idx].id)}}">{{str.val}}</a>
{% endif %}
<span class="form-control col-lg-{{((12/books[key]|length)|int)}}" id="{{key}}-{{books[key][cnt.idx].id}}">
<a href="{{url_for(key, id=books[key][cnt.idx].id)}}">{{str.val}}</a>
</span>
{% set cnt.idx = cnt.idx+1 %}
{% endfor %}
</div>
</table>
{% else %}
{% if key == "notes" or key == "blurb" %}

24
templates/genre.html Normal file
View File

@@ -0,0 +1,24 @@
{% extends "base.html" %} {% block main_content %}
<h3><center>Genre</center></h3>
<div class="container">
<right>
{% if message|length %}
<div class="row alert alert-{{alert}}">
{{message}}
</div>
{% endif %}
<div class="row">
<form class="form form-inline col-xl-12" action="" method="POST">
{{ wtf.form_field( genre_form.id, form_type='inline' ) }}
<div class="col-xl-12">
{{ wtf.form_field( genre_form.name, form_type='horizontal', horizontal_columns=('xl', 2, 10), style="width:100%" ) }}
</div>
<div class="col-xl-12">
<br></br>
</div>
{{ wtf.form_field( genre_form.submit, horizontal_columns=('xl', 2, 2), class="btn btn-primary offset-xl-1 col-xl-2" )}}
{{ wtf.form_field( genre_form.delete, horizontal_columns=('xl', 2, 2), class="btn btn-danger offset-xl-1 col-xl-2" )}}
</form>
</div class="row">
</div class="container">
{% endblock main_content %}

15
templates/genres.html Normal file
View File

@@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block main_content %}
<h3>Publishers</h3>
<table id="book_table" class="table table-striped table-sm" data-toolbar="#toolbar" data-search="true">
<thead>
<tr class="thead-light"><th>Surname</th><th>Firstname(s)</th></tr>
</thead>
<tbody>
{% for publisher in publishers %}
<tr><td><a href="{{url_for('publisher', id=publisher.id )}}">{{publisher.name}}</a></td></tr>
{% endfor %}
</tbody>
</table>
{% endblock main_content %}