Files
books/rating.py

98 lines
4.9 KiB
Python

from wtforms import SubmitField, StringField, HiddenField, SelectField, validators
from flask import request, render_template, redirect
from flask_wtf import FlaskForm
from __main__ import db, app, ma
from sqlalchemy import func, Sequence
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
from status import st, Status
################################################################################
# Class describing Rating in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Rating(db.Model):
id = db.Column(db.Integer, db.Sequence('rating_id_seq'), primary_key=True )
name = db.Column(db.String(50), unique=True, nullable=False)
def __repr__(self):
return "<id: {}, name: {}>".format(self.id,self.name)
################################################################################
# Helper class that inherits a .dump() method to turn class Rating into json / useful in jinja2
################################################################################
class RatingSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Rating
################################################################################
# Helper class that defines a form for rating, used to make html <form>, with field validation (via wtforms)
################################################################################
class RatingForm(FlaskForm):
id = HiddenField()
name = StringField('Name:', [validators.DataRequired()])
submit = SubmitField('Save' )
delete = SubmitField('Delete' )
################################################################################
# Routes for rating data
#
# /ratings -> GET only -> prints out list of all ratings
################################################################################
@app.route("/ratings", methods=["GET"])
def ratings():
objects = Rating.query.order_by('id').all()
return render_template("show_id_name.html", objects=objects, page_title='Show All Ratings', url_base='rating', alert=st.GetAlert(), message=st.GetMessage() )
################################################################################
# /rating -> GET/POST -> creates a new rating type and when created, takes you back to /ratings
################################################################################
@app.route("/rating", methods=["GET", "POST"])
def new_rating():
form = RatingForm(request.form)
if 'name' not in request.form:
return render_template("edit_id_name.html", form=form, page_title='Create new Rating' )
else:
rating = Rating( name=request.form["name"] )
try:
db.session.add(rating)
db.session.commit()
st.SetAlert( "success" )
st.SetMessage( "Created new Rating (id={})".format(rating.id) )
return redirect( '/ratings' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( "<b>Failed to add rating:</b>&nbsp;{}".format( e.orig) )
return render_template("edit_id_name.html", form=form, page_title='Create new Rating', alert=st.GetAlert(), message=st.GetMessage() )
################################################################################
# /rating/<id> -> GET/POST(save or delete) -> shows/edits/delets a single rating
################################################################################
@app.route("/rating/<id>", methods=["GET", "POST"])
def rating(id):
### DDP: should this be request.form or request.values?
form = RatingForm(request.form)
if request.method == 'POST' and form.validate():
try:
rating = Rating.query.get(id)
if 'delete' in request.form:
st.SetMessage("Successfully deleted (id={}, name={})".format( rating.id, rating.name ) )
rating = Rating.query.filter(Rating.id==id).delete()
if 'submit' in request.form:
st.SetMessage("Successfully Updated Rating (id={})".format(id) )
rating.name = request.form['name']
db.session.flush()
db.session.commit()
return redirect( '/ratings' )
except SQLAlchemyError as e:
st.SetAlert( "danger" )
st.SetMessage( "<b>Failed to modity rating:</b>&nbsp;{}".format(e.orig) )
return render_template("edit_id_name.html", form=form, page_title='Edit Rating', alert=st.GetAlert(), message=st.GetMessage() )
else:
rating = Rating.query.get(id)
form = RatingForm(request.values, obj=rating)
return render_template("edit_id_name.html", form=form, page_title='Edit Rating' )
################################################################################
# Gets the Rating matching id from DB, helper func in jinja2 code to show books
################################################################################
def GetRatingById(id):
return Rating.query.get(id).name