-
Notifications
You must be signed in to change notification settings - Fork 0
/
BookModel.py
58 lines (46 loc) · 1.71 KB
/
BookModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from flask_sqlalchemy import SQLAlchemy
from settings import app
from flask import json
db = SQLAlchemy(app)
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
price = db.Column(db.Float, nullable=False)
isbn = db.Column(db.Integer)
def json(self):
return {'name': self.name, 'price': self.price, 'isbn': self.isbn}
def add_book(_name, _price, _isbn):
new_book = Book(name=_name, price=_price, isbn=_isbn)
db.session.add(new_book)
db.session.commit()
def get_book(_isbn):
first_book = Book.query.filter_by(isbn=_isbn).first()
return Book.json(first_book)
def update_book_price(_isbn, _price):
book_to_update = Book.query.filter_by(isbn=_isbn).first()
book_to_update.price = _price
db.session.commit()
def update_book_name(_isbn, _name):
book_to_update = Book.query.filter_by(isbn=_isbn).first()
book_to_update.name = _name
db.session.commit()
def replace_book(_name, _price, _isbn):
book_to_replace = Book.query.filter_by(isbn=_isbn).first()
book_to_replace.name = _name
book_to_replace.price = _price
db.session.commit()
def get_all_books():
return [Book.json(book) for book in Book.query.all()]
def delete_book(_isbn):
is_succesful = Book.query.filter_by(isbn=_isbn).delete()
db.session.commit()
return is_succesful
def __repr__(self):
book_object = {
'id': self.id,
'name': self.name,
'price': self.price,
'isbn': self.isbn
}
return json.dumps(book_object)