From a7bff98bb62cb91a3cce72f975d40a8e3c4b479a Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Thu, 1 May 2025 14:37:27 -0700 Subject: [PATCH 01/30] first commit project set up. --- migrations/README | 1 + migrations/alembic.ini | 50 +++++++++++++++++ migrations/env.py | 113 ++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++ 4 files changed, 188 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..4c9709271 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} From ab1e16ed21b406f451030e4fff49bdb24da6d56c Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Mon, 5 May 2025 18:43:04 -0700 Subject: [PATCH 02/30] define Task model with its attributes. --- app/models/task.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..3eef30e2c 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,10 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from datetime import datetime +from typing import Optional class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] = mapped_column(nullable=False) + description: Mapped[str] = mapped_column(nullable=False) + completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) From 53e3252be28737b601ad48de736a4ce1bc3a61de Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Mon, 5 May 2025 18:44:07 -0700 Subject: [PATCH 03/30] generate migrations file --- migrations/versions/1d99ac8e9bc7_.py | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 migrations/versions/1d99ac8e9bc7_.py diff --git a/migrations/versions/1d99ac8e9bc7_.py b/migrations/versions/1d99ac8e9bc7_.py new file mode 100644 index 000000000..5470b4c5e --- /dev/null +++ b/migrations/versions/1d99ac8e9bc7_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 1d99ac8e9bc7 +Revises: +Create Date: 2025-05-05 18:35:34.289863 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1d99ac8e9bc7' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### From 8dd614daeae2159d3b42ce38f5dd3a8856e60ca2 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 16:28:47 -0700 Subject: [PATCH 04/30] creates Task Model with its helper methods. --- app/models/task.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/models/task.py b/app/models/task.py index 3eef30e2c..be2184db5 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,3 +8,21 @@ class Task(db.Model): title: Mapped[str] = mapped_column(nullable=False) description: Mapped[str] = mapped_column(nullable=False) completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + + # Instance methods + def to_dict(self): + return { + "id": self.id, + "description": self.description, + "title": self.title, + "is_complete": True if self.completed_at else False + } + + + @classmethod + def from_dict(cls, task_data): + new_task = Task(title=task_data["title"], + description=task_data["description"], + completed_at=task_data.get("completed_at") # This will be None if not provided + ) + return new_task From 8a711037706ff51dd9ccbb3d8fdebe1b42290242 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 16:31:36 -0700 Subject: [PATCH 05/30] implements route helper methods - Wave 1. --- app/routes/route_utilities.py | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 app/routes/route_utilities.py diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..5a4a627e1 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,47 @@ +from datetime import datetime +from flask import abort, make_response +from app.models.task import Task +from ..db import db + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + response = {"message": f"{cls.__name__} id{model_id} is invalid" } + abort(make_response(response, 400)) + + query = db.select(cls).where(cls.id == model_id) + model = db.session.scalar(query) + + if not model: + response = {"message": f"{cls.__name__} {model_id} not found"} + abort(make_response(response, 404)) + + return model + + +def create_record(cls, request_body): + try: + new_model = cls.from_dict(request_body) + + except KeyError as error: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_model) + db.session.commit() + print(new_model.title) + return {cls.__name__.lower(): new_model.to_dict()}, 201 + # return new_model.to_dict(), 201 + + +def get_models_with_filters(cls, filters=None): + query = db.select(cls) + + if filters: + for attribute, value in filters.items(): + if hasattr(cls, attribute): + query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) + + models = db.session.scalars(query.order_by(cls.id)) + return [model.to_dict() for model in models] \ No newline at end of file From a9ab6404071310e08106efa01d6bfc2292b500b2 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 16:32:18 -0700 Subject: [PATCH 06/30] Implements CRUD routes for Task model. --- app/routes/task_routes.py | 49 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..e1f467bbe 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,48 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, Response, request +from app.models.task import Task +from app.routes.route_utilities import validate_model, get_models_with_filters, create_record +from ..db import db + + +bp = Blueprint("bp", __name__, url_prefix="/tasks") + + +# POST one +@bp.post("") +def create_task(): + request_body = request.get_json() + + return create_record(Task, request_body) + + +@bp.get("") +def get_all_tasks(): + return get_models_with_filters(Task, request.args) + + +@bp.get("/") +def gets_one_book(task_id): + task = validate_model(Task, task_id) + return {"task": task.to_dict()} + + +@bp.put("/") +def update_task(task_id): + task = validate_model(Task, task_id) + + request_body = request.get_json() + task.title = request_body["title"] + task.description = request_body["description"] + + db.session.commit() + + return Response(status=204, mimetype="application/json") + + +@bp.delete("/") +def delete_task(task_id): + task = validate_model(Task, task_id) + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype="application/json") \ No newline at end of file From 59c898d61cfe9b957f9a360b3dcb5022179e876d Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 16:32:42 -0700 Subject: [PATCH 07/30] registers Task Blueprint --- app/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..617440a9b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from .db import db, migrate from .models import task, goal +from .routes.task_routes import bp as tasks_bp import os def create_app(config=None): @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(tasks_bp) return app From dc545032cae3e4e77a40b14f375db7552460caeb Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 16:33:07 -0700 Subject: [PATCH 08/30] completes test_wave_01. --- tests/test_wave_01.py | 41 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 55475db79..ce3ecce5f 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -3,7 +3,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -14,7 +14,7 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_one_saved_tasks(client, one_task): # Act response = client.get("/tasks") @@ -33,7 +33,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -52,7 +52,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -60,14 +60,10 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -97,7 +93,7 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -117,7 +113,7 @@ def test_update_task(client, one_task): -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -128,14 +124,10 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {"message": "Task 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -146,7 +138,7 @@ def test_delete_task(client, one_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query) == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -154,16 +146,11 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - + assert response_body == {"message": "Task 1 not found"} assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -180,7 +167,7 @@ def test_create_task_must_contain_title(client): assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ From 66b011225a85dfc37fccbcdc60526fd52f0d0f9b Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 21:40:19 -0700 Subject: [PATCH 09/30] implements sonting tasks by title. Wave 2 --- app/models/task.py | 12 ++++++------ app/routes/route_utilities.py | 18 +++++++++++++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index be2184db5..6ebf0d3ee 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -5,8 +5,8 @@ class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - title: Mapped[str] = mapped_column(nullable=False) - description: Mapped[str] = mapped_column(nullable=False) + title: Mapped[str] + description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) # Instance methods @@ -15,14 +15,14 @@ def to_dict(self): "id": self.id, "description": self.description, "title": self.title, - "is_complete": True if self.completed_at else False + "is_complete": self.completed_at is not None } @classmethod def from_dict(cls, task_data): - new_task = Task(title=task_data["title"], + new_task = cls(title=task_data["title"], description=task_data["description"], - completed_at=task_data.get("completed_at") # This will be None if not provided - ) + completed_at=task_data.get("completed_at", None) # This will be None if not provided + ) return new_task diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 5a4a627e1..d2829a19d 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -31,17 +31,29 @@ def create_record(cls, request_body): db.session.add(new_model) db.session.commit() print(new_model.title) - return {cls.__name__.lower(): new_model.to_dict()}, 201 + # return {cls.__name__.lower(): new_model.to_dict()}, 201 + return {"task": new_model.to_dict()}, 201 # return new_model.to_dict(), 201 def get_models_with_filters(cls, filters=None): query = db.select(cls) + sort = None if filters: for attribute, value in filters.items(): + if attribute == "sort": + sort = value + continue if hasattr(cls, attribute): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) - - models = db.session.scalars(query.order_by(cls.id)) + + if sort == "asc": + query = query.order_by(cls.title.asc()) + elif sort == "desc": + query = query.order_by(cls.title.desc()) + else: + query = query.order_by(cls.id) + + models = db.session.scalars(query) return [model.to_dict() for model in models] \ No newline at end of file From cbf6b29a01b64f19e702b1eda885db2688dd987e Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Tue, 6 May 2025 21:40:38 -0700 Subject: [PATCH 10/30] completes tests wave 2 --- tests/test_wave_02.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..651e3aebd 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") From 5dd7e02cdbbe68b61a2b009155e62aa57c54681d Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 00:28:43 -0700 Subject: [PATCH 11/30] implements Task PATCH route to modify completed_at attr. --- app/routes/task_routes.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e1f467bbe..274bd5635 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,3 +1,4 @@ +from datetime import datetime from flask import Blueprint, Response, request from app.models.task import Task from app.routes.route_utilities import validate_model, get_models_with_filters, create_record @@ -45,4 +46,25 @@ def delete_task(task_id): db.session.delete(task) db.session.commit() - return Response(status=204, mimetype="application/json") \ No newline at end of file + return Response(status=204, mimetype="application/json") + + +@bp.patch("//mark_complete") +def mark_task_complete(task_id): + task = validate_model(Task, task_id) + if not task.completed_at: + task.completed_at = datetime.now() + + db.session.commit() + return Response(status=204, mimetype="application/json") + + +@bp.patch("//mark_incomplete") +def mark_task_incomplete(task_id): + task = validate_model(Task, task_id) + if task.completed_at: + task.completed_at = None + + db.session.commit() + return Response(status=204, mimetype="application/json") + From e6fb97c3ddce55dec1b27a6f1990bb5bf55624ee Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 00:29:12 -0700 Subject: [PATCH 12/30] completes tests - Wave 3 --- tests/test_wave_03.py | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..1dce6efbf 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -6,7 +6,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -34,7 +34,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -46,7 +46,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -74,7 +74,7 @@ def test_mark_complete_on_completed_task(client, completed_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -86,7 +86,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -94,14 +94,11 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -109,8 +106,5 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** From 6d12bbe46160b227920000ecd13d0033baf03c9d Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 00:55:11 -0700 Subject: [PATCH 13/30] calls Slack API - Wave 4 --- app/routes/task_routes.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 274bd5635..62e785804 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,9 +1,14 @@ from datetime import datetime +import os +import requests +# from dotenv import load_dotenv from flask import Blueprint, Response, request from app.models.task import Task from app.routes.route_utilities import validate_model, get_models_with_filters, create_record from ..db import db +# load_dotenv() + bp = Blueprint("bp", __name__, url_prefix="/tasks") @@ -52,8 +57,19 @@ def delete_task(task_id): @bp.patch("//mark_complete") def mark_task_complete(task_id): task = validate_model(Task, task_id) + + path = "https://slack.com/api/chat.postMessage" + API_KEY = os.environ.get("API_KEY") + + headers = {"Authorization": f"Bearer {API_KEY}"} + body ={ + "channel": "task-notifications", + "text": f"Someone just completed the task {task.title}" + } + if not task.completed_at: task.completed_at = datetime.now() + slack_post = requests.post(path, headers=headers, json=body ) db.session.commit() return Response(status=204, mimetype="application/json") From fdf21850fb390ec4938e4ae07801e9b0aacaa3f4 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 13:34:52 -0700 Subject: [PATCH 14/30] modifies 'localhost' to '127.0.0.1' in task_list.py - CLI --- cli/task_list.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/task_list.py b/cli/task_list.py index 137f3fa06..93b5e7a0e 100644 --- a/cli/task_list.py +++ b/cli/task_list.py @@ -1,6 +1,6 @@ import requests -url = "http://localhost:5000" +url = "http://127.0.0.1:5000" def parse_response(response): if response.status_code >= 400: From 32f4cdbdd2a9434acdd7a9001259400fc369e5eb Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 14:25:24 -0700 Subject: [PATCH 15/30] refactor create_record() to create_model() in route_utilities. --- app/routes/route_utilities.py | 10 ++++------ app/routes/task_routes.py | 10 +++------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index d2829a19d..3a942848b 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,6 +1,4 @@ -from datetime import datetime from flask import abort, make_response -from app.models.task import Task from ..db import db def validate_model(cls, model_id): @@ -20,9 +18,9 @@ def validate_model(cls, model_id): return model -def create_record(cls, request_body): +def create_model(cls, model_data): try: - new_model = cls.from_dict(request_body) + new_model = cls.from_dict(model_data) except KeyError as error: response = {"details": "Invalid data"} @@ -31,8 +29,8 @@ def create_record(cls, request_body): db.session.add(new_model) db.session.commit() print(new_model.title) - # return {cls.__name__.lower(): new_model.to_dict()}, 201 - return {"task": new_model.to_dict()}, 201 + return {cls.__name__.lower(): new_model.to_dict()}, 201 + # return {"task": new_model.to_dict()}, 201 # return new_model.to_dict(), 201 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 62e785804..806c868df 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,24 +1,20 @@ from datetime import datetime import os -import requests -# from dotenv import load_dotenv +import requests # HTTP library to make a request to Slack API from flask import Blueprint, Response, request from app.models.task import Task -from app.routes.route_utilities import validate_model, get_models_with_filters, create_record +from app.routes.route_utilities import validate_model, get_models_with_filters, create_model from ..db import db -# load_dotenv() - bp = Blueprint("bp", __name__, url_prefix="/tasks") -# POST one @bp.post("") def create_task(): request_body = request.get_json() - return create_record(Task, request_body) + return create_model(Task, request_body) @bp.get("") From 6e9ce52dfc5c96a01e1e1a96feff6458790dc146 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 17:49:45 -0700 Subject: [PATCH 16/30] implements update_model() as route helper function. --- app/routes/route_utilities.py | 12 ++++++++++-- app/routes/task_routes.py | 12 ++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 3a942848b..74f6f07f1 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,4 +1,4 @@ -from flask import abort, make_response +from flask import abort, make_response, Response from ..db import db def validate_model(cls, model_id): @@ -54,4 +54,12 @@ def get_models_with_filters(cls, filters=None): query = query.order_by(cls.id) models = db.session.scalars(query) - return [model.to_dict() for model in models] \ No newline at end of file + return [model.to_dict() for model in models] + + +def update_model(model, model_data): + for attribute, value in model_data.items(): + setattr(model, attribute, value) + + db.session.commit() + return Response(status=204, mimetype="application/json") \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 806c868df..bd4a71348 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,7 +3,7 @@ import requests # HTTP library to make a request to Slack API from flask import Blueprint, Response, request from app.models.task import Task -from app.routes.route_utilities import validate_model, get_models_with_filters, create_model +from app.routes.route_utilities import validate_model, get_models_with_filters, create_model, update_model from ..db import db @@ -31,14 +31,14 @@ def gets_one_book(task_id): @bp.put("/") def update_task(task_id): task = validate_model(Task, task_id) - request_body = request.get_json() - task.title = request_body["title"] - task.description = request_body["description"] + # task.title = request_body["title"] + # task.description = request_body["description"] - db.session.commit() + # db.session.commit() - return Response(status=204, mimetype="application/json") + # return Response(status=204, mimetype="application/json") + return update_model(task, request_body) @bp.delete("/") From 57b6fe3a71e164b4f2baf995ef8e7bc88478feba Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:11:28 -0700 Subject: [PATCH 17/30] implements delete_model as a route helper function. --- app/routes/route_utilities.py | 7 +++++++ app/routes/task_routes.py | 9 +++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 74f6f07f1..f3967d2d4 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -62,4 +62,11 @@ def update_model(model, model_data): setattr(model, attribute, value) db.session.commit() + return Response(status=204, mimetype="application/json") + + +def delete_model(model): + db.session.delete(model) + db.session.commit() + return Response(status=204, mimetype="application/json") \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index bd4a71348..d2aa25ac3 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,7 +3,7 @@ import requests # HTTP library to make a request to Slack API from flask import Blueprint, Response, request from app.models.task import Task -from app.routes.route_utilities import validate_model, get_models_with_filters, create_model, update_model +from app.routes.route_utilities import validate_model, get_models_with_filters, create_model, update_model, delete_model from ..db import db @@ -44,10 +44,11 @@ def update_task(task_id): @bp.delete("/") def delete_task(task_id): task = validate_model(Task, task_id) - db.session.delete(task) - db.session.commit() + # db.session.delete(task) + # db.session.commit() - return Response(status=204, mimetype="application/json") + # return Response(status=204, mimetype="application/json") + return delete_model(task) @bp.patch("//mark_complete") From 6569f97a850787f14faf35c38f1b9d97af11357c Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:15:01 -0700 Subject: [PATCH 18/30] Create Goal model with instance method and class method. --- app/models/goal.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..a7cfdce08 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,21 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db + class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + + + def to_dict(self): + return { + "id": self.id, + "title": self.title + } + + + @classmethod + def from_dict(cls, goal_data): + new_goal= cls(title=goal_data["title"]) + + return new_goal From 4c8e36ce2242beeb9a93fa24fe84a30e019ad394 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:16:26 -0700 Subject: [PATCH 19/30] Generate migration. Goal model added to schema --- .../versions/bc3d12b1a74b_adds_goal_model.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 migrations/versions/bc3d12b1a74b_adds_goal_model.py diff --git a/migrations/versions/bc3d12b1a74b_adds_goal_model.py b/migrations/versions/bc3d12b1a74b_adds_goal_model.py new file mode 100644 index 000000000..12ba33db8 --- /dev/null +++ b/migrations/versions/bc3d12b1a74b_adds_goal_model.py @@ -0,0 +1,32 @@ +"""adds Goal model + +Revision ID: bc3d12b1a74b +Revises: 1d99ac8e9bc7 +Create Date: 2025-05-07 13:53:57.598116 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bc3d12b1a74b' +down_revision = '1d99ac8e9bc7' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.add_column(sa.Column('title', sa.String(), nullable=False)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### From 9eb04758aefc8b075285e2c7f6028e17d51f2240 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:19:54 -0700 Subject: [PATCH 20/30] Define CRUD routes for Goal Model. --- app/routes/goal_routes.py | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..9dcbccc44 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,38 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request +from app.models.goal import Goal +from app.routes.route_utilities import create_model, get_models_with_filters, validate_model, update_model, delete_model +from ..db import db + + +bp = Blueprint("goals_bp", __name__, url_prefix="/goals") + + +@bp.post("") +def create_goal(): + request_body = request.get_json() + + return create_model(Goal, request_body) + + +@bp.get("") +def get_all_goals(): + return get_models_with_filters(Goal, request.args) + + +@bp.get("/") +def get_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return {"goal": goal.to_dict()} + + +@bp.put("/") +def update_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + return update_model(goal, request_body) + +@bp.delete("/") +def delete_goal(goal_id): + goal = validate_model(Goal, goal_id) + return delete_model(goal) \ No newline at end of file From b8b078798c72773248e37758b3f37740f9f3eebb Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:20:40 -0700 Subject: [PATCH 21/30] Register goal blueprint in create_app(). --- app/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 617440a9b..6e447bbf7 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,6 +2,7 @@ from .db import db, migrate from .models import task, goal from .routes.task_routes import bp as tasks_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -20,5 +21,6 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app From 1c3ccbed4fd114a4d705861c34ed532d86f66a9c Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 18:21:42 -0700 Subject: [PATCH 22/30] Complete tests for Wave 5. --- tests/test_wave_05.py | 75 ++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 40 deletions(-) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 222d10cf0..cbe6c2f24 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,9 @@ +from app.models.goal import Goal +from app.db import db import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +14,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -29,7 +31,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +48,19 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,34 +79,36 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 204 + + query = db.select(Goal).where(Goal.id == 1) + goal = db.session.scalar(query) + assert goal.title == "Updated Goal Title" -@pytest.mark.skip(reason="test to be completed by student") + +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -121,28 +122,22 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "message" in response_body - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} + assert db.session.scalars(db.select(Goal)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) From a6bea7691616affab3e36d2d5ccbf7a14bf2bf68 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 23:24:29 -0700 Subject: [PATCH 23/30] Define goal_id FK in Taks model - one goal to many tasks relationship. --- app/models/goal.py | 13 ++++++++++--- app/models/task.py | 18 ++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index a7cfdce08..5f89860fe 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,17 +1,24 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column,relationship from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] + tasks: Mapped[list["Task"]] = relationship(back_populates="goal") def to_dict(self): - return { + goal_dict = { "id": self.id, - "title": self.title + "title": self.title, + # "tasks": [task.to_dict() for task in self.tasks] } + + if self.tasks: + goal_dict["tasks"] = [task.to_dict() for task in self.tasks] + + return goal_dict @classmethod diff --git a/app/models/task.py b/app/models/task.py index 6ebf0d3ee..a8a1b9224 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,22 +1,32 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import ForeignKey +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db from datetime import datetime from typing import Optional + class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") + - # Instance methods def to_dict(self): - return { + task_dict = { "id": self.id, "description": self.description, "title": self.title, - "is_complete": self.completed_at is not None + "is_complete": self.completed_at is not None, + # "goal_id": self.goal.id if self.goal_id else None } + + if self.goal_id: + task_dict["goal_id"] = self.goal_id + + return task_dict @classmethod From 860d4c355d9f1ccafec7534f37f2283d2711b821 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 23:26:00 -0700 Subject: [PATCH 24/30] Generate migration - adds goal_id as FK in task model --- ...a65_adds_goal_id_as_foreign_key_to_task.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 migrations/versions/e14930c61a65_adds_goal_id_as_foreign_key_to_task.py diff --git a/migrations/versions/e14930c61a65_adds_goal_id_as_foreign_key_to_task.py b/migrations/versions/e14930c61a65_adds_goal_id_as_foreign_key_to_task.py new file mode 100644 index 000000000..5519606f1 --- /dev/null +++ b/migrations/versions/e14930c61a65_adds_goal_id_as_foreign_key_to_task.py @@ -0,0 +1,34 @@ +"""Adds goal_id as Foreign Key to Task + +Revision ID: e14930c61a65 +Revises: bc3d12b1a74b +Create Date: 2025-05-07 22:07:39.857172 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e14930c61a65' +down_revision = 'bc3d12b1a74b' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### From 615c005417adc8f24e463b15b1b4b9ec5c30cb14 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 23:27:30 -0700 Subject: [PATCH 25/30] Define Goal nested routes for one to many relationship --- app/routes/goal_routes.py | 41 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 9dcbccc44..e5794532e 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, request from app.models.goal import Goal +from app.models.task import Task from app.routes.route_utilities import create_model, get_models_with_filters, validate_model, update_model, delete_model from ..db import db @@ -10,7 +11,6 @@ @bp.post("") def create_goal(): request_body = request.get_json() - return create_model(Goal, request_body) @@ -22,7 +22,6 @@ def get_all_goals(): @bp.get("/") def get_one_goal(goal_id): goal = validate_model(Goal, goal_id) - return {"goal": goal.to_dict()} @@ -32,7 +31,43 @@ def update_goal(goal_id): request_body = request.get_json() return update_model(goal, request_body) + @bp.delete("/") def delete_goal(goal_id): goal = validate_model(Goal, goal_id) - return delete_model(goal) \ No newline at end of file + return delete_model(goal) + + +# Nested Routes: One goal(parent) to many tasks(child) +@bp.post("//tasks") +def create_task_with_planet(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + task_ids = request_body.get("task_ids", []) + + for task in goal.tasks: + task.goal_id = None + + for task_id in task_ids: + task = validate_model(Task, task_id) + task.goal_id = goal.id # Associate the task with the goal + + db.session.commit() + + return { + "id": goal.id, + "task_ids": task_ids + } + + + +@bp.get("//tasks") +def get_tasks_by_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return dict( + id = goal.id, + title = goal.title, + tasks = [task.to_dict() for task in goal.tasks] + ) \ No newline at end of file From 6fdd934e92ec6e9b479281ec2ac6e4ba8c9e5b7e Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Wed, 7 May 2025 23:28:14 -0700 Subject: [PATCH 26/30] Complete tests for Wave 6. --- tests/test_wave_06.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 0317f835a..46fdd107f 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -3,7 +3,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -25,7 +25,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(db.session.scalar(query).tasks) == 3 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -45,7 +45,7 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on assert len(db.session.scalar(query).tasks) == 2 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act response = client.get("/goals/1/tasks") @@ -53,14 +53,11 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} + assert db.session.scalars(db.select(Goal)).all() == [] - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -77,7 +74,7 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -102,7 +99,7 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json() From fcabbadbc31c94c74fb01144736ce556e16958e0 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Fri, 9 May 2025 00:33:24 -0700 Subject: [PATCH 27/30] Implement validate_multiple_models() as route helper function. --- app/routes/route_utilities.py | 46 +++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index f3967d2d4..81f2d7a5e 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,6 +1,7 @@ from flask import abort, make_response, Response from ..db import db + def validate_model(cls, model_id): try: model_id = int(model_id) @@ -21,17 +22,14 @@ def validate_model(cls, model_id): def create_model(cls, model_data): try: new_model = cls.from_dict(model_data) - except KeyError as error: response = {"details": "Invalid data"} abort(make_response(response, 400)) db.session.add(new_model) db.session.commit() - print(new_model.title) + return {cls.__name__.lower(): new_model.to_dict()}, 201 - # return {"task": new_model.to_dict()}, 201 - # return new_model.to_dict(), 201 def get_models_with_filters(cls, filters=None): @@ -54,6 +52,7 @@ def get_models_with_filters(cls, filters=None): query = query.order_by(cls.id) models = db.session.scalars(query) + return [model.to_dict() for model in models] @@ -62,6 +61,7 @@ def update_model(model, model_data): setattr(model, attribute, value) db.session.commit() + return Response(status=204, mimetype="application/json") @@ -69,4 +69,40 @@ def delete_model(model): db.session.delete(model) db.session.commit() - return Response(status=204, mimetype="application/json") \ No newline at end of file + return Response(status=204, mimetype="application/json") + + +def validate_multiple_models(cls, id_list): + """ + Validates that all IDs in the given list exist for the specified model class in one. + + Parameters: + - cls: model class + - id_list: list of model ids + + Returns: + - A list of model instances matching the given IDs. + + Aborts: + - 400 if any ID is not a valid integer. + - 404 if one or more IDs are not found in the database. + """ + + try: + id_list = [int(id) for id in id_list] + except: + response = {"message": f"One or more {cls.__name__} IDs are not valid integers" } + abort(make_response(response, 400)) + + # Query for all models matching the given IDs + models = db.session.scalars(db.select(cls).where(cls.id.in_(id_list))).all() + + # Query for all models matching the given IDs + if len(models) != len(set(id_list)): + found_ids = {model.id for model in models} + missing_ids = set(id_list) - found_ids + + response = {"message": f"{cls.__name__} IDs not found: {missing_ids}"} + abort(make_response(response, 404)) + + return models \ No newline at end of file From 6a8b803d50e91556d7b0f09164a66725884e9a67 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Fri, 9 May 2025 00:36:54 -0700 Subject: [PATCH 28/30] Refactor assign_task_to_goal() - post nested route. Wave 6 --- app/routes/goal_routes.py | 58 +++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index e5794532e..6af2f323c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, request from app.models.goal import Goal from app.models.task import Task -from app.routes.route_utilities import create_model, get_models_with_filters, validate_model, update_model, delete_model +from app.routes.route_utilities import create_model, get_models_with_filters, validate_model, update_model, delete_model, validate_multiple_models from ..db import db @@ -39,35 +39,51 @@ def delete_goal(goal_id): # Nested Routes: One goal(parent) to many tasks(child) +@bp.get("//tasks") +def get_tasks_by_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return dict( + id = goal.id, + title = goal.title, + tasks = [task.to_dict() for task in goal.tasks] + ) + + @bp.post("//tasks") -def create_task_with_planet(goal_id): +def assign_tasks_to_goal(goal_id): + """ + Associates the given task IDs with a goal by its ID, and unlinks any previously associated tasks not in the list. + + Validates all task IDs and updates the database accordingly. Returns the goal ID and the updated list of task IDs. + + Request: { "task_ids": [1, 2, 3] } + Response: { "id": 1, "task_ids": [1, 2, 3] } + """ + goal = validate_model(Goal, goal_id) request_body = request.get_json() - task_ids = request_body.get("task_ids", []) - for task in goal.tasks: - task.goal_id = None + # Validate list taks ids in one query to db + valid_tasks = validate_multiple_models(Task, task_ids) - for task_id in task_ids: - task = validate_model(Task, task_id) - task.goal_id = goal.id # Associate the task with the goal + # Unlink tasks that are no longer assigned to this goal + for task_in_goal in goal.tasks: + if task_in_goal.id not in task_ids: + task_in_goal.goal_id = None + + valid_tasks_ids = [] + + # Assign valid tasks to this goal + for task in valid_tasks: + valid_tasks_ids.append(task.id) + if task.goal_id != goal.id: + task.goal_id = goal.id db.session.commit() return { "id": goal.id, - "task_ids": task_ids + "task_ids": valid_tasks_ids } - - - -@bp.get("//tasks") -def get_tasks_by_goal(goal_id): - goal = validate_model(Goal, goal_id) - - return dict( - id = goal.id, - title = goal.title, - tasks = [task.to_dict() for task in goal.tasks] - ) \ No newline at end of file From 2bfe64c1b46b003df7e55551a3b9ef3ac432e423 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Fri, 9 May 2025 00:40:09 -0700 Subject: [PATCH 29/30] Import type_checking for goal and task models. --- app/models/goal.py | 6 +++++- app/models/task.py | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/app/models/goal.py b/app/models/goal.py index 5f89860fe..679acf3be 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,6 +2,11 @@ from ..db import db +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .task import Task + + class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] @@ -12,7 +17,6 @@ def to_dict(self): goal_dict = { "id": self.id, "title": self.title, - # "tasks": [task.to_dict() for task in self.tasks] } if self.tasks: diff --git a/app/models/task.py b/app/models/task.py index a8a1b9224..39f025650 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -5,6 +5,11 @@ from typing import Optional +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .goal import Goal + + class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] From beb1fdf5c7753ed7742cbc350320bb50619f6a31 Mon Sep 17 00:00:00 2001 From: Lina Martinez Date: Fri, 9 May 2025 00:52:36 -0700 Subject: [PATCH 30/30] Clean up code by removing comments and adjusting spacing. --- app/models/task.py | 4 ++-- app/routes/route_utilities.py | 3 ++- app/routes/task_routes.py | 23 ++++++++++++----------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 39f025650..6839a628b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -25,7 +25,6 @@ def to_dict(self): "description": self.description, "title": self.title, "is_complete": self.completed_at is not None, - # "goal_id": self.goal.id if self.goal_id else None } if self.goal_id: @@ -38,6 +37,7 @@ def to_dict(self): def from_dict(cls, task_data): new_task = cls(title=task_data["title"], description=task_data["description"], - completed_at=task_data.get("completed_at", None) # This will be None if not provided + completed_at=task_data.get("completed_at", None) ) + return new_task diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 81f2d7a5e..5f4280688 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -41,6 +41,7 @@ def get_models_with_filters(cls, filters=None): if attribute == "sort": sort = value continue + if hasattr(cls, attribute): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) @@ -87,7 +88,7 @@ def validate_multiple_models(cls, id_list): - 400 if any ID is not a valid integer. - 404 if one or more IDs are not found in the database. """ - + try: id_list = [int(id) for id in id_list] except: diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d2aa25ac3..5293e7cd8 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -23,8 +23,9 @@ def get_all_tasks(): @bp.get("/") -def gets_one_book(task_id): +def gets_one_task(task_id): task = validate_model(Task, task_id) + return {"task": task.to_dict()} @@ -32,32 +33,29 @@ def gets_one_book(task_id): def update_task(task_id): task = validate_model(Task, task_id) request_body = request.get_json() - # task.title = request_body["title"] - # task.description = request_body["description"] - - # db.session.commit() - # return Response(status=204, mimetype="application/json") return update_model(task, request_body) @bp.delete("/") def delete_task(task_id): task = validate_model(Task, task_id) - # db.session.delete(task) - # db.session.commit() - - # return Response(status=204, mimetype="application/json") + return delete_model(task) @bp.patch("//mark_complete") def mark_task_complete(task_id): + """ + Marks a task as complete and sends a Slack notification. + + If the task is not already completed, sets the `completed_at` timestamp and posts a message to Slack. + Returns a 204 No Content response. + """ task = validate_model(Task, task_id) path = "https://slack.com/api/chat.postMessage" API_KEY = os.environ.get("API_KEY") - headers = {"Authorization": f"Bearer {API_KEY}"} body ={ "channel": "task-notifications", @@ -69,15 +67,18 @@ def mark_task_complete(task_id): slack_post = requests.post(path, headers=headers, json=body ) db.session.commit() + return Response(status=204, mimetype="application/json") @bp.patch("//mark_incomplete") def mark_task_incomplete(task_id): task = validate_model(Task, task_id) + if task.completed_at: task.completed_at = None db.session.commit() + return Response(status=204, mimetype="application/json")