Files
books/series.py

129 lines
6.7 KiB
Python

from wtforms import SubmitField, StringField, HiddenField, validators, TextAreaField, IntegerField
from flask_wtf import FlaskForm
from flask import request, render_template, redirect
from wtforms.fields.html5 import DateField
from __main__ import db, app, ma
from sqlalchemy.exc import SQLAlchemyError
from status import st, Status
################################################################################
# Class describing Series in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Series(db.Model):
id = db.Column(db.Integer, db.Sequence('series_id_seq'), primary_key=True)
title = db.Column(db.String(100), unique=False, nullable=False)
num_books = db.Column(db.Integer, nullable=False)
calcd_rating = db.Column(db.String(10), unique=False, nullable=False)
note = db.Column(db.Text)
def __repr__(self):
return "<id: {}, title: {}, num_books: {}, calcd_rating: {}, note: {}>".format(self.id, self.title, self.num_books, self.calcd_rating, self.note)
################################################################################
# Helper class that inherits a .dump() method to turn class Series into json / useful in jinja2
################################################################################
class SeriesSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Series
ordered = True
################################################################################
# Helper class that defines a form for series, used to make html <form>, with field validation (via wtforms)
################################################################################
class SeriesForm(FlaskForm):
id = HiddenField()
title = StringField('Title:', [validators.DataRequired()])
num_books = IntegerField('Number of Books:', [validators.NumberRange(min=1)])
calcd_rating = StringField('Avg Rating:' )
note = TextAreaField('Notes:')
submit = SubmitField('Save' )
delete = SubmitField('Delete' )
def CalcAvgRating(sid):
res=db.engine.execute("select round(avg(to_number(r.name, '99')),1) as rating from book b, rating r, series s, book_series_link bsl where s.id={} and s.id = bsl.series_id and bsl.book_id = b.id and b.rating = r.id and r.name ~ E'^\\\\d+$'".format(sid))
for row in res:
print( row )
return row.rating
def ListOfSeriesWithMissingBooks():
res=db.engine.execute("select id, title, num_books, count from ( select s.id, s.title, s.num_books, count(bsl.book_id) from series s, book_series_link bsl where s.id = bsl.series_id group by s.id ) as foo where num_books > count")
tmp=[]
for row in res:
tmp.append({'id': row[0], 'title': row[1]})
return tmp
################################################################################
# Routes for series data
#
# /seriess -> GET only -> prints out list of all seriess
################################################################################
@app.route("/seriess", methods=["GET"])
def seriess():
seriess = Series.query.all()
return render_template("seriess.html", seriess=seriess, message=st.GetMessage(), alert=st.GetAlert())
################################################################################
# /series -> GET/POST -> creates a new series type and when created, takes you back to /seriess
################################################################################
@app.route("/series", methods=["GET", "POST"])
def new_series():
form = SeriesForm(request.form)
page_title='Create new Series'
if 'title' not in request.form:
return render_template("series.html", form=form, page_title=page_title, message=st.GetMessage(), alert=st.GetAlert() )
else:
series = Series( title=request.form["title"], num_books=request.form["num_books"], note=request.form["note"], calcd_rating=0 )
try:
db.session.add(series)
db.session.commit()
st.SetMessage( "Created new Series (id={})".format(series.id) )
return redirect( '/seriess' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( "<b>Failed to add Series:</b>&nbsp;{}".format( e.orig) )
return render_template("series.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() )
################################################################################
# /series/<id> -> GET/POST(save or delete) -> shows/edits/delets a single series
################################################################################
@app.route("/series/<id>", methods=["GET", "POST"])
def series(id):
### DDP: should this be request.form or request.values?
form = SeriesForm(request.form)
page_title='Edit Series'
if request.method == 'POST':
try:
series = Series.query.get(id)
if 'delete' in request.form:
st.SetMessage("Successfully deleted (id={}, title={})".format( series.id, series.title ) )
series = Series.query.filter(Series.id==id).delete()
if 'submit' in request.form and form.validate():
st.SetMessage("Successfully Updated Series (id={})".format(id) )
series.title = request.form['title']
series.num_books = request.form['num_books']
series.calcd_rating = CalcAvgRating(id)
series.note = request.form['note']
else:
message="<b>Failed to update Series:</b>"
for field in form.errors:
message = "{}<br>{}={}".format( message, field, form.errors[field] )
st.SetAlert("danger")
st.SetMessage(message)
return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() )
db.session.commit()
return redirect( '/seriess' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( "<b>Failed to modify Series:</b>&nbsp;{}".format(e.orig) )
return render_template("edit_id_name.html", form=form, page_title=page_title, alert=st.GetAlert(), message=st.GetMessage() )
else:
series = Series.query.get(id)
form = SeriesForm(request.values, obj=series)
return render_template("series.html", form=form, page_title=page_title, message=st.GetMessage(), alert=st.GetAlert() )
################################################################################
# Gets the Series matching id from DB, helper func in jinja2 code to show books
################################################################################
def GetSeriesById(id):
return Series.query.get(id).name