pulled apart main to make a self-contained author.py... Weird use of importing from __main__ rather than main.py, and ordering the import to after the db object was created seems to be the secret sauce

This commit is contained in:
2020-11-14 15:03:37 +11:00
parent f8d31dd325
commit 3831c0a03b
2 changed files with 64 additions and 46 deletions

View File

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

50
main.py
View File

@@ -3,20 +3,20 @@ from flask import render_template
from flask import request from flask import request
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow from flask_marshmallow import Marshmallow
from author import AuthorForm
from flask_bootstrap import Bootstrap from flask_bootstrap import Bootstrap
DB_URL = 'postgresql+psycopg2://ddp:NWNlfa01@127.0.0.1:5432/library'
app = Flask(__name__) app = Flask(__name__)
### what is this value? I gather I should chagne it?
DB_URL = 'postgresql+psycopg2://ddp:NWNlfa01@127.0.0.1:5432/library'
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
### what is this value? I gather I should chagne it?
app.config.from_mapping( SECRET_KEY=b'\xd6\x04\xbdj\xfe\xed$c\x1e@\xad\x0f\x13,@G') app.config.from_mapping( SECRET_KEY=b'\xd6\x04\xbdj\xfe\xed$c\x1e@\xad\x0f\x13,@G')
db = SQLAlchemy(app) db = SQLAlchemy(app)
ma = Marshmallow(app) ma = Marshmallow(app)
Bootstrap(app) Bootstrap(app)
from author import Author, AuthorForm, AuthorSchema
####################################### CLASSES / DB model ####################################### ####################################### CLASSES / DB model #######################################
book_author_link = db.Table('book_author_link', db.Model.metadata, book_author_link = db.Table('book_author_link', db.Model.metadata,
db.Column('book_id', db.Integer, db.ForeignKey('book.id')), db.Column('book_id', db.Integer, db.ForeignKey('book.id')),
@@ -64,14 +64,6 @@ class Book(db.Model):
def __repr__(self): 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 ) 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 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 "<id: {}, firstnames: {}, surname: {}>".format(self.id,self.firstnames, self.surname)
class Publisher(db.Model): class Publisher(db.Model):
id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
name = db.Column(db.String(50), unique=False, nullable=False) name = db.Column(db.String(50), unique=False, nullable=False)
@@ -87,10 +79,6 @@ class Genre_Lst(db.Model):
def __repr__(self): def __repr__(self):
return "<id: {}, genre: {}>".format(self.id, self.genre) return "<id: {}, genre: {}>".format(self.id, self.genre)
### setup serializer schemas, to make returning books/authors easier
class AuthorSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Author
class PublisherSchema(ma.SQLAlchemyAutoSchema): class PublisherSchema(ma.SQLAlchemyAutoSchema):
class Meta: model = Publisher class Meta: model = Publisher
@@ -158,36 +146,6 @@ def book(id):
return render_template("book.html", books=book_s, subs=sub_book ) return render_template("book.html", books=book_s, subs=sub_book )
@app.route("/authors", methods=["GET"])
def authors():
authors = Author.query.all()
return render_template("authors.html", authors=authors)
@app.route("/author/<id>", methods=["GET", "POST"])
def author(id):
### DDP: should this be request.form or request.values?
alert="Success"
author_form = AuthorForm(request.form)
if request.method == 'POST' and author_form.validate():
id = request.form['id']
author = Author.query.get(id)
try:
request.form['submit']
except:
message="Sorry, Deleting unsupported at present"
alert="Danger"
else:
print( "seems to be saving" )
author.firstnames = request.form['firstnames']
author.surname = request.form['surname']
db.session.commit()
message="Successfully Updated Author (id={})".format(id)
else:
author = Author.query.get(id)
author_form = AuthorForm(request.values, obj=author)
message=""
return render_template("author.html", author=author, alert=alert, message=message, author_form=author_form)
@app.route("/", methods=["GET"]) @app.route("/", methods=["GET"])
def main_page(): def main_page():
return render_template("main.html") return render_template("main.html")