Kay Ashaolu - Instructor
Aishwarya Sriram - TA
requirements.txt
:SQLAlchemy
and Flask-SQLAlchemy
. pip install -r requirements.txt
requirements.txt
bust the cache layer, ensuring latest dependencies.models/
folder.from db import db
class ItemModel(db.Model):
__tablename__ = 'items'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
price = db.Column(db.Float(precision=2), nullable=False)
store_id = db.Column(db.Integer, db.ForeignKey('stores.id'), nullable=False)
# Relationship to store will be added later
Maps a row in the items
table to a Python object.
from db import db
class StoreModel(db.Model):
__tablename__ = 'stores'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
# One-to-many relationship with items
items = db.relationship('ItemModel', back_populates='store', lazy='dynamic')
Defines a store and its one-to-many relationship with items.
ItemModel
has a store_id
linking to StoreModel
.db.ForeignKey
to enforce the relationship.db.relationship
with back_populates
for bidirectional access.lazy='dynamic'
delays fetching related items until explicitly requested.ItemModel
: store = db.relationship('StoreModel', back_populates='items')
StoreModel
: items = db.relationship('ItemModel', back_populates='store', lazy='dynamic')
item.store
and items via store.items.all()
. from db import db
import models
def create_app(db_url=None):
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = db_url or \
os.getenv('DATABASE_URL', 'sqlite:///data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
@app.before_first_request
def create_tables():
db.create_all()
return app
sqlite:///data.db
create_app
) that returns a configured Flask instance. with app.app_context():
db.create_all()
item_data = {'name': 'chair', 'price': 20.5, 'store_id': 1}
item = ItemModel(**item_data)
db.session.add(item)
db.session.commit()
db.session.commit()
writes changes to disk. from sqlalchemy.exc import SQLAlchemyError
try:
db.session.add(item)
db.session.commit()
except SQLAlchemyError as e:
db.session.rollback()
abort(500, message="An error occurred while inserting the item.")
item = ItemModel.query.get_or_404(item_id)
item = ItemModel.query.get(item_id)
if item:
item.name = item_data['name']
item.price = item_data['price']
else:
item = ItemModel(id=item_id, **item_data)
db.session.add(item)
db.session.commit()
items = ItemModel.query.all()
return items # Serialized using a schema with many=True
all()
method to fetch a complete list. item = ItemModel.query.get_or_404(item_id)
db.session.delete(item)
db.session.commit()
return {"message": "Item deleted."}, 200
items = db.relationship('ItemModel', back_populates='store',
cascade="all, delete", lazy='dynamic')
from db import db
class TagModel(db.Model):
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
store_id = db.Column(db.Integer, db.ForeignKey('stores.id'), nullable=False)
# Relationship back to store
store = db.relationship('StoreModel', back_populates='tags')
tags = db.relationship('TagModel', back_populates='store', lazy='dynamic')
class PlainTagSchema(ma.Schema):
class Meta:
fields = ("id", "name")
tags = fields.Nested(PlainTagSchema, many=True, dump_only=True)
from db import db
class ItemTags(db.Model):
__tablename__ = 'item_tags'
id = db.Column(db.Integer, primary_key=True)
item_id = db.Column(db.Integer, db.ForeignKey('items.id'), nullable=False)
tag_id = db.Column(db.Integer, db.ForeignKey('tags.id'), nullable=False)
models/__init__.py
for auto-creation. items = db.relationship('ItemModel', secondary='item_tags',
back_populates='tags')
tags = db.relationship('TagModel', secondary='item_tags',
back_populates='items')
item = ItemModel.query.get_or_404(item_id)
tag = TagModel.query.get_or_404(tag_id)
item.tags.append(tag)
db.session.commit()
item.tags.remove(tag)
db.session.commit()