61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
from flask import Flask
|
|
from flask import render_template
|
|
from flask import request
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
import logging
|
|
|
|
DB_URL = 'postgresql+psycopg2://ddp:NWNlfa01@127.0.0.1:5432/library'
|
|
app = Flask(__name__)
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
|
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
|
db = SQLAlchemy(app)
|
|
|
|
####################################### CLASSES / DB model #######################################
|
|
book_author_link = db.Table('book_author_link', db.Model.metadata,
|
|
db.Column('book_id', db.Integer, db.ForeignKey('book.id')),
|
|
db.Column('author_id', db.Integer, db.ForeignKey('author.id'))
|
|
)
|
|
|
|
class Book(db.Model):
|
|
id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
|
|
title = db.Column(db.String(100), unique=True, nullable=False)
|
|
author = db.relationship('Author', secondary=book_author_link)
|
|
|
|
def __repr__(self):
|
|
return "<title: {}, id: {} author: {} author.firstnames {}>".format(self.title, self.id, self.author, self.id )
|
|
# return "<title: {}, id: {} author: {} author.firstnames {}>".format(self.title, self.id, self.author, self.author.firstnames )
|
|
|
|
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)
|
|
|
|
# book = db.relationship('Book', secondary=book_author_link )
|
|
|
|
def __repr__(self):
|
|
return "<firstnames: {}, surname: {}>".format(self.firstnames, self.surname )
|
|
# return "<firstnames: {}, surname: {}, book: {}>".format(self.firstnames, self.surname, self.book)
|
|
|
|
####################################### ROUTES #######################################
|
|
@app.route("/books", methods=["GET"])
|
|
def books():
|
|
if request.form:
|
|
print(request.form)
|
|
books = Book.query.all()
|
|
return render_template("books.html", books=books)
|
|
|
|
@app.route("/book/<id>", methods=["GET"])
|
|
def book(id):
|
|
book = Book.query.get(id)
|
|
print( book )
|
|
return render_template("books.html", books=book )
|
|
|
|
@app.route("/authors", methods=["GET"])
|
|
def author():
|
|
authors = Author.query.all()
|
|
return render_template("author.html", authors=authors)
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", debug=True)
|
|
|