Skip to content

Commit

Permalink
Merge pull request #103 from tecladocode/develop
Browse files Browse the repository at this point in the history
  • Loading branch information
jslvtr authored Dec 14, 2022
2 parents 77fe34e + 25684cb commit e601a2c
Show file tree
Hide file tree
Showing 65 changed files with 527 additions and 41 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
from models.user import UserModel
from models.item import ItemModel
from models.tag import TagModel
from models.store import StoreModel
from models.item_tags import ItemsTags
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
flask
flask-smorest
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: Delete models with relationships
description: Tell SQLAlchemy what to do with related models when you delete the parent.
---

# Delete models with relationships using cascades

When you delete a model that has a relationship to other models that still exist, the default behavior in SQLAlchemy with PostgreSQL is to raise an error. This is because SQLAlchemy does not want to allow you to accidentally delete data that is still being used by other models.

Let's say you have a `Store 1` that has two items, `Item 1` and `Item 2`. If you try to delete Store 1 without first deleting Item 1 and Item 2, SQLAlchemy will raise an error because the items are still related to the store.

This means the items have a **Foreign Key** that references the store you're trying to delete. If the store actually was deleted, the items have a store ID that references something that doesn't exist.

To fix this, you can use a feature called "cascading deletes". Cascading deletes allow you to specify that when a model is deleted, any related models should also be deleted automatically.

SQLAlchemy makes it easy to add cascades to our models, here's how you might do that!

```python title="models/store.py"
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)

# highlight-start
items = db.relationship("ItemModel", back_populates="store", lazy="dynamic", cascade="all, delete")
# highlight-end
```

Remember that `StoreModel` and `ItemModel` have a one-to-many relationship, where each store can have multiple items, and each item belongs to a single store.

The `cascade="all,delete"` argument in the `relationship()` call for the `StoreModel.items` attribute specifies that when a store is deleted, all of its related items should also be deleted.

If you add a `cascade` on the relationship in the `ItemModel`, then when an item is deleted, its related store should also be deleted. This is not what we want, so we won't add a cascade to `ItemModel`.

With this code in place, if you try to delete a store that still has items, the items will be deleted automatically along with the store. This will allow you to delete the store without having to delete the items individually.

For more information, I strongly recommend reading [the official documentation](https://docs.sqlalchemy.org/en/20/orm/cascades.html#delete)! There are also other cascade options you can pass in depending on what you want to happen to related models when the parent changes or is deleted.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FLASK_APP=app
FLASK_DEBUG=True
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM python:3.10
EXPOSE 5000
WORKDIR /app
COPY ./requirements.txt requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
COPY . .
CMD ["flask", "run", "--host", "0.0.0.0"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from flask import Flask
from flask_smorest import Api

from db import db

import models

from resources.item import blp as ItemBlueprint
from resources.store import blp as StoreBlueprint


def create_app(db_url=None):
app = Flask(__name__)
app.config["API_TITLE"] = "Stores REST API"
app.config["API_VERSION"] = "v1"
app.config["OPENAPI_VERSION"] = "3.0.3"
app.config["OPENAPI_URL_PREFIX"] = "/"
app.config["OPENAPI_SWAGGER_UI_PATH"] = "/swagger-ui"
app.config[
"OPENAPI_SWAGGER_UI_URL"
] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
app.config["SQLALCHEMY_DATABASE_URI"] = db_url or "sqlite:///data.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
db.init_app(app)
api = Api(app)

with app.app_context():
db.create_all()

api.register_blueprint(ItemBlueprint)
api.register_blueprint(StoreBlueprint)

return app
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from models.item import ItemModel
from models.store import StoreModel
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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=False, nullable=False)
price = db.Column(db.Float(precision=2), unique=False, nullable=False)

store_id = db.Column(
db.Integer, db.ForeignKey("stores.id"), unique=False, nullable=False
)
store = db.relationship("StoreModel", back_populates="items")
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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)

items = db.relationship(
"ItemModel", back_populates="store", lazy="dynamic", cascade="all, delete"
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
flask
flask-sqlalchemy
flask-smorest
python-dotenv
marshmallow
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from sqlalchemy.exc import SQLAlchemyError

from db import db
from models import ItemModel
from schemas import ItemSchema, ItemUpdateSchema

blp = Blueprint("Items", "items", description="Operations on items")


@blp.route("/item/<string:item_id>")
class Item(MethodView):
@blp.response(200, ItemSchema)
def get(self, item_id):
item = ItemModel.query.get_or_404(item_id)
return item

def delete(self, item_id):
item = ItemModel.query.get_or_404(item_id)
db.session.delete(item)
db.session.commit()
return {"message": "Item deleted."}

@blp.arguments(ItemUpdateSchema)
@blp.response(200, ItemSchema)
def put(self, item_data, item_id):
item = ItemModel.query.get(item_id)

if item:
item.price = item_data["price"]
item.name = item_data["name"]
else:
item = ItemModel(id=item_id, **item_data)

db.session.add(item)
db.session.commit()

return item


@blp.route("/item")
class ItemList(MethodView):
@blp.response(200, ItemSchema(many=True))
def get(self):
return ItemModel.query.all()

@blp.arguments(ItemSchema)
@blp.response(201, ItemSchema)
def post(self, item_data):
item = ItemModel(**item_data)

try:
db.session.add(item)
db.session.commit()
except SQLAlchemyError:
abort(500, message="An error occurred while inserting the item.")

return item
Loading

0 comments on commit e601a2c

Please sign in to comment.