From 3831c0a03b9f1f1847ff3532e0fbbefa32ccde4a Mon Sep 17 00:00:00 2001 From: Damien De Paoli Date: Sat, 14 Nov 2020 15:03:37 +1100 Subject: [PATCH] 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 --- author.py | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.py | 50 ++++------------------------------------------ 2 files changed, 64 insertions(+), 46 deletions(-) diff --git a/author.py b/author.py index eb315f5..acf6e79 100644 --- a/author.py +++ b/author.py @@ -1,8 +1,68 @@ 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 "".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
, with field validation (via wtforms) +################################################################################ class AuthorForm(Form): id = HiddenField() firstnames = StringField('FirstName(s):', [validators.DataRequired()]) surname = StringField('Surname:', [validators.DataRequired()]) submit = SubmitField('Save' ) 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/ -> GET/POST(save or delete) -> shows/edits/delets a single author +################################################################################ +@app.route("/author/", 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) diff --git a/main.py b/main.py index 72db533..f161770 100644 --- a/main.py +++ b/main.py @@ -3,20 +3,20 @@ from flask import render_template from flask import request from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow -from author import AuthorForm from flask_bootstrap import Bootstrap - -DB_URL = 'postgresql+psycopg2://ddp:NWNlfa01@127.0.0.1:5432/library' 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_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') db = SQLAlchemy(app) ma = Marshmallow(app) Bootstrap(app) +from author import Author, AuthorForm, AuthorSchema + ####################################### CLASSES / DB model ####################################### book_author_link = db.Table('book_author_link', db.Model.metadata, db.Column('book_id', db.Integer, db.ForeignKey('book.id')), @@ -64,14 +64,6 @@ class Book(db.Model): 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) @@ -87,10 +79,6 @@ class Genre_Lst(db.Model): 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 - class PublisherSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Publisher @@ -158,36 +146,6 @@ def book(id): 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/", 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"]) def main_page(): return render_template("main.html")