From 54ef790987b8c9ea5b84ad404ff8f3bb75db565d Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 30 Oct 2025 13:32:51 -0700 Subject: [PATCH 01/17] initial setup --- 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 32389d01a6bdea9e7b9756bd935eb454c325469e Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 30 Oct 2025 17:30:41 -0700 Subject: [PATCH 02/17] create task tests passing --- app/__init__.py | 2 ++ app/models/task.py | 11 ++++++++ app/routes/task_routes.py | 37 +++++++++++++++++++++++++- migrations/versions/7afae7105aba_.py | 39 ++++++++++++++++++++++++++++ migrations/versions/e83fdca5a6d0_.py | 32 +++++++++++++++++++++++ migrations/versions/f3b4bd1ef407_.py | 32 +++++++++++++++++++++++ tests/test_wave_01.py | 32 +++++++++++------------ 7 files changed, 168 insertions(+), 17 deletions(-) create mode 100644 migrations/versions/7afae7105aba_.py create mode 100644 migrations/versions/e83fdca5a6d0_.py create mode 100644 migrations/versions/f3b4bd1ef407_.py diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..c5a60f1f7 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,4 +1,5 @@ from flask import Flask +from .routes.task_routes import task_bp from .db import db, migrate from .models import task, goal import os @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(task_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..b1c7d9a0a 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,16 @@ from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import Boolean from ..db import db +from datetime import datetime class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + description: Mapped[str] + completed_at: Mapped[datetime | None] + + def to_dict(self): + return {"id": self.id, "title": self.title, "description": self.description, "is_complete": True if self.completed_at != None else False} + + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..d75c2db07 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,36 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, abort, make_response, request, Response +from ..db import db +from app.models.task import Task + +task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") + +@task_bp.post("") +def create_task(): + request_body = request.get_json() + title = request_body["title"] + description = request_body["description"] + completed_at = request_body["completed_at"] + + new_task = Task(title = title, description = description, completed_at= completed_at) + db.session.add(new_task) + db.session.commit() + + response = new_task.to_dict() + + # { + # "title": new_task.title, + # "description": new_task.description, + # "is_complete": True if new_task.completed_at == None else False + # } + return response, 201 + + + + + +# Tasks should contain these attributes. The tests require the following columns to be named exactly as title, description, and completed_at. + +# id: a primary key for each task +# title: text to name the task +# description: text to describe the task +# completed_at: a datetime that represents the date that a task is completed on. Can be nullable, and contain a null value. A task with a null value for completed_at has not been completed. When we create a new task, completed_at should be null AKA None in Python. diff --git a/migrations/versions/7afae7105aba_.py b/migrations/versions/7afae7105aba_.py new file mode 100644 index 000000000..20cd292a2 --- /dev/null +++ b/migrations/versions/7afae7105aba_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 7afae7105aba +Revises: +Create Date: 2025-10-30 14:00:47.099049 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7afae7105aba' +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 ### diff --git a/migrations/versions/e83fdca5a6d0_.py b/migrations/versions/e83fdca5a6d0_.py new file mode 100644 index 000000000..12f02edff --- /dev/null +++ b/migrations/versions/e83fdca5a6d0_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: e83fdca5a6d0 +Revises: 7afae7105aba +Create Date: 2025-10-30 16:39:49.224949 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e83fdca5a6d0' +down_revision = '7afae7105aba' +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('is_complete', sa.Boolean(), nullable=False)) + + # ### 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_column('is_complete') + + # ### end Alembic commands ### diff --git a/migrations/versions/f3b4bd1ef407_.py b/migrations/versions/f3b4bd1ef407_.py new file mode 100644 index 000000000..25e431121 --- /dev/null +++ b/migrations/versions/f3b4bd1ef407_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: f3b4bd1ef407 +Revises: e83fdca5a6d0 +Create Date: 2025-10-30 17:29:41.408331 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f3b4bd1ef407' +down_revision = 'e83fdca5a6d0' +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.drop_column('is_complete') + + # ### 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.add_column(sa.Column('is_complete', sa.BOOLEAN(), autoincrement=False, nullable=False)) + + # ### end Alembic commands ### diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fac95a0a3..bf3118db6 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,7 @@ 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_task_to_dict(): #Arrange new_task = Task(id = 1, title="Make My Bed", @@ -19,7 +19,7 @@ def test_task_to_dict(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict_missing_id(): #Arrange new_task = Task(title="Make My Bed", @@ -36,7 +36,7 @@ def test_task_to_dict_missing_id(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict_missing_title(): #Arrange new_task = Task(id = 1, @@ -53,7 +53,7 @@ def test_task_to_dict_missing_title(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict(): #Arrange task_dict = { @@ -70,7 +70,7 @@ def test_task_from_dict(): assert task_obj.description == "Start the day off right!" assert task_obj.completed_at is 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_task_from_dict_no_title(): #Arrange task_dict = { @@ -82,7 +82,7 @@ def test_task_from_dict_no_title(): with pytest.raises(KeyError, match = 'title'): Task.from_dict(task_dict) -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict_no_description(): #Arrange task_dict = { @@ -94,7 +94,7 @@ def test_task_from_dict_no_description(): with pytest.raises(KeyError, match = 'description'): Task.from_dict(task_dict) -@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") @@ -105,7 +105,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") @@ -124,7 +124,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") @@ -140,7 +140,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") @@ -155,7 +155,7 @@ def test_get_task_not_found(client): # ***************************************************************** -@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={ @@ -181,7 +181,7 @@ def test_create_task(client): assert new_task.description == "Test Description" 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={ @@ -201,7 +201,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={ @@ -219,7 +219,7 @@ def test_update_task_not_found(client): # ***************************************************************** -@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") @@ -247,7 +247,7 @@ def test_delete_task_not_found(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_title(client): # Act response = client.post("/tasks", json={ @@ -264,7 +264,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 20d4216f6146f959b8b475d1bce70713c5b9cca2 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Sun, 2 Nov 2025 13:26:42 -0800 Subject: [PATCH 03/17] from_dict added to Task model --- app/models/task.py | 10 ++++++++-- app/routes/task_routes.py | 23 ++++++++++++++++++----- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index b1c7d9a0a..047aaea82 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,6 +11,12 @@ class Task(db.Model): def to_dict(self): return {"id": self.id, "title": self.title, "description": self.description, "is_complete": True if self.completed_at != None else False} - - + + @classmethod + def from_dict(cls, task_data): + new_task = Task(title = task_data["title"], + description = task_data["description"], + completed_at = None if task_data["is_complete"] is False else cls.completed_at) + + return new_task diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d75c2db07..fbb5f6268 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -7,11 +7,11 @@ @task_bp.post("") def create_task(): request_body = request.get_json() - title = request_body["title"] - description = request_body["description"] - completed_at = request_body["completed_at"] - - new_task = Task(title = title, description = description, completed_at= completed_at) + # title = request_body["title"] + # description = request_body["description"] + # completed_at = request_body["completed_at"] + new_task = Task.from_dict(request_body) + # new_task = Task(title = title, description = description, completed_at= completed_at) db.session.add(new_task) db.session.commit() @@ -24,6 +24,19 @@ def create_task(): # } return response, 201 +@task_bp.get("") +def get_all_tasks(): + query = db.select(Task) + + query = query.order_by(Task.id) + tasks = db.session.scalars(query) + + tasks_response = [] + for task in tasks: + task_dict = task.to_dict() + tasks_response.append(task_dict) + return tasks_response + From 41802d578a140d87c14f9c94417f29185e40df80 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Mon, 3 Nov 2025 13:12:32 -0800 Subject: [PATCH 04/17] wave 1 completed --- app/models/task.py | 4 ++-- app/routes/route_utilities.py | 21 ++++++++++++++++++ app/routes/task_routes.py | 42 ++++++++++++++++++++++++++--------- tests/test_wave_01.py | 11 +++++---- 4 files changed, 61 insertions(+), 17 deletions(-) create mode 100644 app/routes/route_utilities.py diff --git a/app/models/task.py b/app/models/task.py index 047aaea82..5319eb2d0 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -14,9 +14,9 @@ def to_dict(self): @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 = None if task_data["is_complete"] is False else cls.completed_at) + completed_at = None if ("is_complete" not in task_data or task_data["is_complete"] is False) else cls.completed_at) return new_task diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..0e6011542 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,21 @@ +from flask import abort, make_response +from ..db import db + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + response = {"message": f"{cls.__name__} {model_id} 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 + + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index fbb5f6268..22f8a01d1 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,27 +1,25 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task +from .route_utilities import validate_model task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @task_bp.post("") def create_task(): request_body = request.get_json() - # title = request_body["title"] - # description = request_body["description"] - # completed_at = request_body["completed_at"] - new_task = Task.from_dict(request_body) - # new_task = Task(title = title, description = description, completed_at= completed_at) + + try: + new_task = Task.from_dict(request_body) + except: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + db.session.add(new_task) db.session.commit() response = new_task.to_dict() - # { - # "title": new_task.title, - # "description": new_task.description, - # "is_complete": True if new_task.completed_at == None else False - # } return response, 201 @task_bp.get("") @@ -35,10 +33,32 @@ def get_all_tasks(): for task in tasks: task_dict = task.to_dict() tasks_response.append(task_dict) - return tasks_response + return tasks_response + +@task_bp.get("") +def get_one_task(task_id): + task = validate_model(Task, task_id) + return task.to_dict() + +@task_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.completed_at = request_body["completed_at"] + db.session.commit() + return Response(status=204, mimetype="application/json") +@task_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") # Tasks should contain these attributes. The tests require the following columns to be named exactly as title, description, and completed_at. diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index bf3118db6..809d212f2 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -148,8 +148,9 @@ 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") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -212,8 +213,9 @@ def test_update_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") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -230,7 +232,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") @@ -238,8 +240,9 @@ def test_delete_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") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From 1b5b6d427032263c5a6813415c0ac162b060f069 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Tue, 4 Nov 2025 13:55:20 -0800 Subject: [PATCH 05/17] wave 2 complete with passing tests --- app/routes/route_utilities.py | 10 ++++++++++ app/routes/task_routes.py | 11 +++++++++-- tests/test_wave_02.py | 4 ++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 0e6011542..a4d23b70d 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -17,5 +17,15 @@ def validate_model(cls, model_id): return model +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)) + models_response = [model.to_dict() for model in models] + return models_response diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 22f8a01d1..e37af9b80 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task -from .route_utilities import validate_model +from .route_utilities import validate_model, get_models_with_filters task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -26,7 +26,13 @@ def create_task(): def get_all_tasks(): query = db.select(Task) - query = query.order_by(Task.id) + sort_param = request.args.get('sort', None) + + if sort_param == "desc": + query = query.order_by(Task.title.desc()) + elif sort_param == "asc": + query = query.order_by(Task.title.asc()) + tasks = db.session.scalars(query) tasks_response = [] @@ -35,6 +41,7 @@ def get_all_tasks(): tasks_response.append(task_dict) return tasks_response + @task_bp.get("") def get_one_task(task_id): task = validate_model(Task, task_id) diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..c9a76e6b1 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 ab829f5fea30a65cac81c15ddc797d0634715fb1 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Tue, 4 Nov 2025 16:59:02 -0800 Subject: [PATCH 06/17] wave 3 and tests pass --- app/routes/task_routes.py | 22 ++++++++++++++++++++++ tests/test_wave_03.py | 18 ++++++++++-------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e37af9b80..c5cb1d2d4 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,6 +2,7 @@ from ..db import db from app.models.task import Task from .route_utilities import validate_model, get_models_with_filters +from datetime import datetime task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -68,6 +69,27 @@ def delete_task(task_id): return Response(status=204, mimetype="application/json") +@task_bp.patch("//mark_complete") +def patch_complete_task(task_id): + #Mark Complete on an Incomplete Task; Mark Complete on a Completed Task + task = validate_model(Task, task_id) + + task.completed_at = datetime.now() + db.session.commit() + + return Response(status=204, mimetype="application/json") + + +@task_bp.patch("//mark_incomplete") +def patch_incomplete_task(task_id): + #Mark Incomplete on a Completed Task; Mark Incomplete on an Incomplete Task + task = validate_model(Task, task_id) + + task.completed_at = None + db.session.commit() + + return Response(status=204, mimetype="application/json") + # Tasks should contain these attributes. The tests require the following columns to be named exactly as title, description, and completed_at. # id: a primary key for each task diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..48bc4237c 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,15 @@ 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") + #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 +110,9 @@ 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") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From 52997f07e7368524cb9a553efdbef80d1c8be596 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Tue, 4 Nov 2025 21:54:53 -0800 Subject: [PATCH 07/17] slack API connection successful --- app/routes/task_routes.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index c5cb1d2d4..d3bd0d24b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,6 +3,8 @@ from app.models.task import Task from .route_utilities import validate_model, get_models_with_filters from datetime import datetime +import os +import requests task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -77,6 +79,8 @@ def patch_complete_task(task_id): task.completed_at = datetime.now() db.session.commit() + generate_slack_notification(task.title) + return Response(status=204, mimetype="application/json") @@ -90,9 +94,28 @@ def patch_incomplete_task(task_id): return Response(status=204, mimetype="application/json") + +def generate_slack_notification(model_attribute): + path = "https://slack.com/api/chat.postMessage" + SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") + + headers = { + "Authorization": f"Bearer {SLACK_TOKEN}" + } + json = { + "channel": "task-notifications", + "text": f"Someone just completed the task {model_attribute}" + } + + slack_response = requests.post(path, headers=headers, json=json) + + + # Tasks should contain these attributes. The tests require the following columns to be named exactly as title, description, and completed_at. # id: a primary key for each task # title: text to name the task # description: text to describe the task # completed_at: a datetime that represents the date that a task is completed on. Can be nullable, and contain a null value. A task with a null value for completed_at has not been completed. When we create a new task, completed_at should be null AKA None in Python. + + From f7b87531696f64ff6b2b9752754d2dd94c8d78f8 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Wed, 5 Nov 2025 16:00:08 -0800 Subject: [PATCH 08/17] some refactors and goal routes and helpers setup- wave 05 --- app/__init__.py | 4 +++- app/models/goal.py | 12 ++++++++++++ app/models/task.py | 5 ++++- app/routes/goal_routes.py | 16 +++++++++++++++- app/routes/route_utilities.py | 8 +++++++- app/routes/task_routes.py | 25 +++++++++++-------------- 6 files changed, 52 insertions(+), 18 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index c5a60f1f7..a3fd2bd59 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,5 +1,6 @@ from flask import Flask -from .routes.task_routes import task_bp +from .routes.task_routes import bp as task_bp +from .routes.goal_routes import bp as goal_bp from .db import db, migrate from .models import task, goal import os @@ -20,5 +21,6 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(task_bp) + app.register_blueprint(goal_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..a299c9a99 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,15 @@ 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 diff --git a/app/models/task.py b/app/models/task.py index 5319eb2d0..94211baf4 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -10,7 +10,10 @@ class Task(db.Model): completed_at: Mapped[datetime | None] def to_dict(self): - return {"id": self.id, "title": self.title, "description": self.description, "is_complete": True if self.completed_at != None else False} + return {"id": self.id, + "title": self.title, + "description": self.description, + "is_complete": True if self.completed_at != None else False} @classmethod def from_dict(cls, task_data): diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..8ca13d2ed 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,15 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, abort, make_response, request, Response +from ..db import db +from app.models.goal import Goal +from .route_utilities import validate_model, get_models_with_filters, delete_model +from datetime import datetime +import os +import requests + +bp = Blueprint("goal_bp", __name__, url_prefix="/goals") + + +@bp.delete("/") +def delete_task(goal_id): + goal_response = delete_model(Goal, goal_id) + return goal_response \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index a4d23b70d..e844eafdb 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): @@ -29,3 +29,9 @@ def get_models_with_filters(cls, filters=None): models_response = [model.to_dict() for model in models] return models_response +def delete_model(cls, model_id): + model = validate_model(cls, model_id) + 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 d3bd0d24b..29cd092cd 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,14 +1,14 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task -from .route_utilities import validate_model, get_models_with_filters +from .route_utilities import validate_model, get_models_with_filters, delete_model from datetime import datetime import os import requests -task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") +bp = Blueprint("task_bp", __name__, url_prefix="/tasks") -@task_bp.post("") +@bp.post("") def create_task(): request_body = request.get_json() @@ -25,7 +25,7 @@ def create_task(): return response, 201 -@task_bp.get("") +@bp.get("") def get_all_tasks(): query = db.select(Task) @@ -45,12 +45,12 @@ def get_all_tasks(): return tasks_response -@task_bp.get("") +@bp.get("") def get_one_task(task_id): task = validate_model(Task, task_id) return task.to_dict() -@task_bp.put("/") +@bp.put("/") def update_task(task_id): task = validate_model(Task, task_id) request_body = request.get_json() @@ -62,16 +62,13 @@ def update_task(task_id): return Response(status=204, mimetype="application/json") -@task_bp.delete("/") +@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") + task_response = delete_model(Task, task_id) + return task_response -@task_bp.patch("//mark_complete") +@bp.patch("//mark_complete") def patch_complete_task(task_id): #Mark Complete on an Incomplete Task; Mark Complete on a Completed Task task = validate_model(Task, task_id) @@ -84,7 +81,7 @@ def patch_complete_task(task_id): return Response(status=204, mimetype="application/json") -@task_bp.patch("//mark_incomplete") +@bp.patch("//mark_incomplete") def patch_incomplete_task(task_id): #Mark Incomplete on a Completed Task; Mark Incomplete on an Incomplete Task task = validate_model(Task, task_id) From 15bde6aafd6d773b08b8b23dc8d93199fadd8e1f Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Wed, 5 Nov 2025 16:09:12 -0800 Subject: [PATCH 09/17] removed uncessary delete helper --- app/routes/goal_routes.py | 9 ++++++--- app/routes/task_routes.py | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 8ca13d2ed..f50e4ca58 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -10,6 +10,9 @@ @bp.delete("/") -def delete_task(goal_id): - goal_response = delete_model(Goal, goal_id) - return goal_response \ No newline at end of file +def delete_goal(goal_id): + goal = validate_model(Goal, goal_id) + db.session.delete(goal) + 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 29cd092cd..dcd791784 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task -from .route_utilities import validate_model, get_models_with_filters, delete_model +from .route_utilities import validate_model, get_models_with_filters from datetime import datetime import os import requests @@ -64,8 +64,11 @@ def update_task(task_id): @bp.delete("/") def delete_task(task_id): - task_response = delete_model(Task, task_id) - return task_response + task = validate_model(Task, task_id) + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype="application/json") @bp.patch("//mark_complete") From 38df37e5b1e07e4e8a77897186abc55d7d11b506 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Wed, 5 Nov 2025 16:09:39 -0800 Subject: [PATCH 10/17] removed uncessary delete helper-2 --- app/routes/route_utilities.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index e844eafdb..543500e50 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -28,10 +28,3 @@ def get_models_with_filters(cls, filters=None): models = db.session.scalars(query.order_by(cls.id)) models_response = [model.to_dict() for model in models] return models_response - -def delete_model(cls, model_id): - model = validate_model(cls, model_id) - db.session.delete(model) - db.session.commit() - - return Response(status=204, mimetype="application/json") \ No newline at end of file From 342ef7f9a9bc8ecbe44cc57f461bd3fd5ed30d83 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Wed, 5 Nov 2025 16:31:54 -0800 Subject: [PATCH 11/17] wave 5 complete --- app/routes/goal_routes.py | 55 +++++++++++++++++++++++++++++++-- tests/test_wave_05.py | 64 ++++++++++++++++++++++++++------------- 2 files changed, 96 insertions(+), 23 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index f50e4ca58..505cd0775 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,13 +1,63 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.goal import Goal -from .route_utilities import validate_model, get_models_with_filters, delete_model +from .route_utilities import validate_model, get_models_with_filters from datetime import datetime import os import requests bp = Blueprint("goal_bp", __name__, url_prefix="/goals") +@bp.post("") +def create_goal(): + request_body = request.get_json() + + try: + new_goal = Goal.from_dict(request_body) + except: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_goal) + db.session.commit() + + response = new_goal.to_dict() + + return response, 201 + +@bp.get("") +def get_all_goals(): + query = db.select(Goal) + + sort_param = request.args.get('sort', None) + + if sort_param == "desc": + query = query.order_by(Goal.title.desc()) + elif sort_param == "asc": + query = query.order_by(Goal.title.asc()) + + goals = db.session.scalars(query) + + goals_response = [] + for goal in goals: + goal_dict = goal.to_dict() + goals_response.append(goal_dict) + return goals_response + +@bp.get("/") +def get_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + return goal.to_dict() + +@bp.put("/") +def update_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + goal.title = request_body["title"] + db.session.commit() + + return Response(status=204, mimetype="application/json") @bp.delete("/") def delete_goal(goal_id): @@ -15,4 +65,5 @@ def delete_goal(goal_id): db.session.delete(goal) db.session.commit() - return Response(status=204, mimetype="application/json") \ No newline at end of file + return Response(status=204, mimetype="application/json") + diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b7cc330ae..af7c39638 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,8 @@ 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_goal_to_dict(): #Arrange new_goal = Goal(id=1, title="Seize the Day!") @@ -13,7 +14,7 @@ def test_goal_to_dict(): assert goal_dict["id"] == 1 assert goal_dict["title"] == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict_no_id(): #Arrange new_goal = Goal(title="Seize the Day!") @@ -25,7 +26,7 @@ def test_goal_to_dict_no_id(): assert goal_dict["id"] is None assert goal_dict["title"] == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict_no_title(): #Arrange new_goal = Goal(id=1) @@ -39,7 +40,7 @@ def test_goal_to_dict_no_title(): -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict(): #Arrange goal_dict = { @@ -52,7 +53,7 @@ def test_goal_from_dict(): #Assert assert goal_obj.title == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict_no_title(): #Arrange goal_dict = { @@ -63,7 +64,7 @@ def test_goal_from_dict_no_title(): Goal.from_dict(goal_dict) -@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") @@ -74,7 +75,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") @@ -91,7 +92,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") @@ -105,22 +106,24 @@ 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") + #raise Exception("Complete test") # Assert # ---- Complete Test ---- # assertion 1 goes here + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} # assertion 2 goes here # ---- Complete Test ---- -@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={ @@ -136,34 +139,47 @@ 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" + }) + + query = db.select(Goal).where(Goal.id == 1) + goal = db.session.scalar(query) # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert goal.title == "Updated Goal Title" # assertion 2 goes here + assert response.status_code == 204 # assertion 3 goes here # ---- Complete Assertions Here ---- -@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") + #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 + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"message": "Goal 1 not found"} # ---- Complete Assertions Here ---- -@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") @@ -177,28 +193,34 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "message" in response_body + assert response_body == {"message": "Goal 1 not found"} - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** + -@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") + #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 + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"message": "Goal 1 not found"} # ---- Complete Assertions Here ---- -@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 0f2da89ecdfdec3666d289d2a6fad3f22c8099cc Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 14:17:09 -0800 Subject: [PATCH 12/17] first wave 6 test passes --- app/models/goal.py | 24 +++++++++-- app/models/task.py | 24 +++++++++-- app/routes/goal_routes.py | 19 ++++++++- app/routes/route_utilities.py | 14 +++++++ .../cb0cd81602d5_added_relationship.py | 40 +++++++++++++++++++ tests/test_wave_06.py | 12 +++--- 6 files changed, 118 insertions(+), 15 deletions(-) create mode 100644 migrations/versions/cb0cd81602d5_added_relationship.py diff --git a/app/models/goal.py b/app/models/goal.py index a299c9a99..21b74427e 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,17 +1,33 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +#from sqlalchemy import ForeignKey from ..db import db +from typing import Optional +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] - + #task_ids: Mapped[Optional[int]] = mapped_column(ForeignKey("task.id")) + tasks: Mapped[list["Task"]] = relationship(back_populates="goal") + def to_dict(self): - return {"id": self.id, + goal_as_dict = {"id": self.id, "title": self.title } + + if self.tasks: + goal_as_dict["task_ids"] = [task.id for task in self.tasks] + + return goal_as_dict @classmethod def from_dict(cls, goal_data): - new_goal = cls(title = goal_data["title"]) + # task_ids = goal_data.get("task_ids") + # task_id_list = [task.id for task in task_ids] + new_goal = cls(title = goal_data["title"]) + #tasks = Task() + return new_goal diff --git a/app/models/task.py b/app/models/task.py index 94211baf4..64b096e70 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,25 +1,41 @@ -from sqlalchemy.orm import Mapped, mapped_column -from sqlalchemy import Boolean +from sqlalchemy.orm import Mapped, mapped_column, relationship +#from sqlalchemy import Boolean +from sqlalchemy import ForeignKey from ..db import db from datetime import datetime +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] description: Mapped[str] completed_at: Mapped[datetime | None] + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") def to_dict(self): - return {"id": self.id, + task_as_dict = {"id": self.id, "title": self.title, "description": self.description, "is_complete": True if self.completed_at != None else False} + + if self.goal: + task_as_dict["goal"] = self.goal.title + + return task_as_dict @classmethod def from_dict(cls, task_data): + goal_id = task_data.get("goal_id") new_task = cls(title = task_data["title"], description = task_data["description"], - completed_at = None if ("is_complete" not in task_data or task_data["is_complete"] is False) else cls.completed_at) + completed_at = None if ("is_complete" not in task_data + or task_data["is_complete"] is False) + else cls.completed_at, + goal_id = goal_id) return new_task diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 505cd0775..e1ad1d14c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,7 +1,8 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.goal import Goal -from .route_utilities import validate_model, get_models_with_filters +from app.models.task import Task +from .route_utilities import validate_model, get_models_with_filters, create_model from datetime import datetime import os import requests @@ -67,3 +68,19 @@ def delete_goal(goal_id): return Response(status=204, mimetype="application/json") +@bp.post("//tasks") +def creat_tasks_for_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + task_id_list = request_body.get("task_ids", []) + for task_id in task_id_list: + task = validate_model(Task, task_id) + task.goal = goal + + db.session.commit() + + response = goal.to_dict() + del response["title"] + + return response, 200 + diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 543500e50..2c620c1a0 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -17,6 +17,7 @@ def validate_model(cls, model_id): return model + def get_models_with_filters(cls, filters=None): query = db.select(cls) @@ -28,3 +29,16 @@ def get_models_with_filters(cls, filters=None): models = db.session.scalars(query.order_by(cls.id)) models_response = [model.to_dict() for model in models] return models_response + +def create_model(cls, model_data): + try: + new_model = cls.from_dict(model_data) + + except KeyError as error: + response = {"message": f"Invalid request: missing {error.args[0]}"} + abort(make_response(response, 400)) + + db.session.add(new_model) + db.session.commit() + + return new_model.to_dict(), 201 \ No newline at end of file diff --git a/migrations/versions/cb0cd81602d5_added_relationship.py b/migrations/versions/cb0cd81602d5_added_relationship.py new file mode 100644 index 000000000..baa5be3e2 --- /dev/null +++ b/migrations/versions/cb0cd81602d5_added_relationship.py @@ -0,0 +1,40 @@ +"""added relationship + +Revision ID: cb0cd81602d5 +Revises: f3b4bd1ef407 +Create Date: 2025-11-06 12:31:03.359602 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'cb0cd81602d5' +down_revision = 'f3b4bd1ef407' +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)) + + 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') + + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 727fce93a..3eb225013 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_overwrites_existing_tasks(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_overwrites_existing_tasks(client, one_task_belong 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") @@ -60,7 +60,7 @@ def test_get_tasks_for_specific_goal_no_goal(client): # ***************************************************************** -@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 +77,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 +102,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 86d0640442cd7e3809af31f1bbf50f067f38aa6a Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 15:57:21 -0800 Subject: [PATCH 13/17] refactoring, current working condition- two test failing --- app/models/goal.py | 7 +++-- app/routes/goal_routes.py | 25 +++++++++++++---- app/routes/route_utilities.py | 4 +-- tests/test_wave_06.py | 4 +-- tests/test_wave_07.py | 53 +++++++++++++++++++++++++---------- 5 files changed, 67 insertions(+), 26 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 21b74427e..73577e19e 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -11,12 +11,15 @@ class Goal(db.Model): title: Mapped[str] #task_ids: Mapped[Optional[int]] = mapped_column(ForeignKey("task.id")) tasks: Mapped[list["Task"]] = relationship(back_populates="goal") - + def to_dict(self): goal_as_dict = {"id": self.id, - "title": self.title + "title": self.title, + "tasks": [task.to_dict() for task in self.tasks] } + if not self.tasks: + goal_as_dict["tasks"] = [] if self.tasks: goal_as_dict["task_ids"] = [task.id for task in self.tasks] diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index e1ad1d14c..979ca704e 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -22,7 +22,8 @@ def create_goal(): db.session.add(new_goal) db.session.commit() - response = new_goal.to_dict() + #response = new_goal.to_dict() + response = {"id": new_goal.id, "title": new_goal.title} return response, 201 @@ -41,14 +42,17 @@ def get_all_goals(): goals_response = [] for goal in goals: - goal_dict = goal.to_dict() + #goal_dict = goal.to_dict() + goal_dict = {"id": goal.id, "title": goal.title} + goals_response.append(goal_dict) return goals_response @bp.get("/") def get_one_goal(goal_id): goal = validate_model(Goal, goal_id) - return goal.to_dict() + goal_dict = {"id": goal.id, "title": goal.title} + return goal_dict #goal.to_dict() @bp.put("/") def update_goal(goal_id): @@ -73,14 +77,25 @@ def creat_tasks_for_goal(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() task_id_list = request_body.get("task_ids", []) + + for task_obj in list(goal.tasks): + task_obj.goal = None + for task_id in task_id_list: task = validate_model(Task, task_id) task.goal = goal db.session.commit() - response = goal.to_dict() - del response["title"] + response = {"id": goal.id, "task_ids": task_id_list} return response, 200 + + +@bp.get("//tasks") +def get_tasks_for_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + response = goal.to_dict() + #response = goal.task.to_dict() + return response \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 2c620c1a0..651ae1113 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -5,7 +5,7 @@ def validate_model(cls, model_id): try: model_id = int(model_id) except: - response = {"message": f"{cls.__name__} {model_id} invalid"} + response = {"details": "Invalid data"} abort(make_response(response, 400)) query = db.select(cls).where(cls.id == model_id) @@ -35,7 +35,7 @@ def create_model(cls, model_data): new_model = cls.from_dict(model_data) except KeyError as error: - response = {"message": f"Invalid request: missing {error.args[0]}"} + response = {"details": "Invalid data"} abort(make_response(response, 400)) db.session.add(new_model) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 3eb225013..431bf6746 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -53,8 +53,9 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -101,7 +102,6 @@ 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") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") diff --git a/tests/test_wave_07.py b/tests/test_wave_07.py index 7e7cef55a..814bf03fc 100644 --- a/tests/test_wave_07.py +++ b/tests/test_wave_07.py @@ -4,7 +4,7 @@ from app.models.task import Task from app.routes.route_utilities import create_model, validate_model -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_task(client, three_tasks): #Act task_1 = validate_model(Task, 1) @@ -24,7 +24,7 @@ def test_route_utilities_validate_model_with_task(client, three_tasks): assert task_3.title == "Pay my outstanding tickets 😭" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_task_invalid_id(client, three_tasks): #Act & Assert # Calling `validate_model` without being invoked by a route will @@ -34,26 +34,33 @@ def test_route_utilities_validate_model_with_task_invalid_id(client, three_tasks # Test that the correct status code and response message are returned response = e.value.get_response() + response_body = response.get_json() assert response.status_code == 400 + assert response_body == {"details": "Invalid data"} - raise Exception("Complete test with an assertion about the response body") + #raise Exception("Complete test with an assertion about the response body") # ***************************************************************************** # ** Complete test with an assertion about the 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_route_utilities_validate_model_with_task_missing_id(client, three_tasks): #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Task, 4) - raise Exception("Complete test with assertion status code and response body") + response = e.value.get_response() + response_body = response.get_json() + assert response.status_code == 404 + assert response_body == {"message": "Task 4 not found"} + + #raise Exception("Complete test with assertion status code and response body") # ***************************************************************************** # **Complete test with assertion about status code 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_route_utilities_validate_model_with_goal(client, one_goal): #Act goal_1 = validate_model(Goal, 1) @@ -62,29 +69,39 @@ def test_route_utilities_validate_model_with_goal(client, one_goal): assert goal_1.id == 1 assert goal_1.title == "Build a habit of going outside daily" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_goal_invalid_id(client, one_goal): #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Goal, "One") - raise Exception("Complete test with assertion status code and response body") + response = e.value.get_response() + response_body = response.get_json() + assert response.status_code == 400 + assert response_body == {"details": "Invalid data"} + + #raise Exception("Complete test with assertion status code and response body") # ***************************************************************************** # **Complete test with assertion about status code 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_route_utilities_validate_model_with_goal_missing_id(client, one_goal): #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Goal, 4) - raise Exception("Complete test with assertion status code and response body") + response = e.value.get_response() + response_body = response.get_json() + assert response.status_code == 404 + assert response_body == {"message": "Goal 4 not found"} + + #raise Exception("Complete test with assertion status code and response body") # ***************************************************************************** # **Complete test with assertion about status code 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_route_utilities_create_model_with_task(client): #Arrange request_body = { @@ -103,7 +120,7 @@ def test_route_utilities_create_model_with_task(client): assert response[0]["is_complete"] == False assert response[1] == 201 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_task_missing_title(client): #Arrange request_body = { @@ -120,7 +137,7 @@ def test_route_utilities_create_model_with_task_missing_title(client): assert response.get_json() == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_goal(client): #Arrange request_body = { @@ -135,7 +152,7 @@ def test_route_utilities_create_model_with_goal(client): assert response[0]["title"] == "Seize the Day!" assert response[1] == 201 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_goal_missing_title(client): #Arrange request_body = { @@ -145,7 +162,13 @@ def test_route_utilities_create_model_with_goal_missing_title(client): with pytest.raises(HTTPException) as e: create_model(Goal, request_body) - raise Exception("Complete test with assertion status code and response body") + response = e.value.get_response() + response_body = response.get_json() + assert response.status_code == 400 + assert response_body == {"details": "Invalid data"} + + + #raise Exception("Complete test with assertion status code and response body") # ***************************************************************************** # **Complete test with assertion about status code response body*************** # ***************************************************************************** From 52fbdd50680236a270e6aba67d5a78fc1a6bb7cf Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 16:37:32 -0800 Subject: [PATCH 14/17] all tests passing --- app/models/goal.py | 11 +++++++---- app/models/task.py | 9 +++++---- app/routes/goal_routes.py | 3 ++- app/routes/task_routes.py | 2 +- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 73577e19e..94bbe3977 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -12,19 +12,22 @@ class Goal(db.Model): #task_ids: Mapped[Optional[int]] = mapped_column(ForeignKey("task.id")) tasks: Mapped[list["Task"]] = relationship(back_populates="goal") - def to_dict(self): + def to_dict(self, include_task_ids = False, include_goal_id_in_tasks = False): goal_as_dict = {"id": self.id, "title": self.title, - "tasks": [task.to_dict() for task in self.tasks] + "tasks": [task.to_dict(include_goal_id = include_goal_id_in_tasks) for task in self.tasks] } - + if not self.tasks: goal_as_dict["tasks"] = [] - if self.tasks: + if include_task_ids and self.tasks: goal_as_dict["task_ids"] = [task.id for task in self.tasks] return goal_as_dict + #def to_dict_add_keys(): + + @classmethod def from_dict(cls, goal_data): # task_ids = goal_data.get("task_ids") diff --git a/app/models/task.py b/app/models/task.py index 64b096e70..18b8b8edb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -16,14 +16,15 @@ class Task(db.Model): goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") - def to_dict(self): + def to_dict(self, include_goal_id = False): task_as_dict = {"id": self.id, "title": self.title, "description": self.description, "is_complete": True if self.completed_at != None else False} - - if self.goal: - task_as_dict["goal"] = self.goal.title + if include_goal_id and self.goal_id is not None: + task_as_dict["goal_id"] = self.goal_id + # if self.goal: + # task_as_dict["goal"] = self.goal.title return task_as_dict diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 979ca704e..da2a00e1b 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -96,6 +96,7 @@ def creat_tasks_for_goal(goal_id): @bp.get("//tasks") def get_tasks_for_one_goal(goal_id): goal = validate_model(Goal, goal_id) - response = goal.to_dict() + response = goal.to_dict(include_goal_id_in_tasks = True) + #del response["task_ids"] #response = goal.task.to_dict() return response \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index dcd791784..0ff28c66e 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -48,7 +48,7 @@ def get_all_tasks(): @bp.get("") def get_one_task(task_id): task = validate_model(Task, task_id) - return task.to_dict() + return task.to_dict(include_goal_id = True) @bp.put("/") def update_task(task_id): From 5f7b4ded95eec666a83ed3220d7236260d1d1cc3 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 17:28:36 -0800 Subject: [PATCH 15/17] refactored and added new helper in route_utilities --- app/models/goal.py | 24 +++++------------ app/models/task.py | 3 --- app/routes/goal_routes.py | 46 +++++-------------------------- app/routes/route_utilities.py | 30 ++++++++++++--------- app/routes/task_routes.py | 51 +++-------------------------------- 5 files changed, 35 insertions(+), 119 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 94bbe3977..d20f7aa43 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,7 +1,5 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship -#from sqlalchemy import ForeignKey from ..db import db -from typing import Optional from typing import TYPE_CHECKING if TYPE_CHECKING: from .task import Task @@ -9,31 +7,23 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] - #task_ids: Mapped[Optional[int]] = mapped_column(ForeignKey("task.id")) tasks: Mapped[list["Task"]] = relationship(back_populates="goal") - def to_dict(self, include_task_ids = False, include_goal_id_in_tasks = False): + def to_dict(self, include_tasks=False, include_task_ids = False, include_goal_id_in_tasks = False): goal_as_dict = {"id": self.id, "title": self.title, - "tasks": [task.to_dict(include_goal_id = include_goal_id_in_tasks) for task in self.tasks] } - if not self.tasks: + if include_tasks: goal_as_dict["tasks"] = [] - if include_task_ids and self.tasks: + if self.tasks and include_tasks: + goal_as_dict["tasks"] = [task.to_dict(include_goal_id = include_goal_id_in_tasks) for task in self.tasks] + elif include_task_ids and self.tasks: goal_as_dict["task_ids"] = [task.id for task in self.tasks] return goal_as_dict - - #def to_dict_add_keys(): - @classmethod - def from_dict(cls, goal_data): - # task_ids = goal_data.get("task_ids") - # task_id_list = [task.id for task in task_ids] - - new_goal = cls(title = goal_data["title"]) - #tasks = Task() - + def from_dict(cls, goal_data): + new_goal = cls(title = goal_data["title"]) return new_goal diff --git a/app/models/task.py b/app/models/task.py index 18b8b8edb..17426890b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,4 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship -#from sqlalchemy import Boolean from sqlalchemy import ForeignKey from ..db import db from datetime import datetime @@ -23,8 +22,6 @@ def to_dict(self, include_goal_id = False): "is_complete": True if self.completed_at != None else False} if include_goal_id and self.goal_id is not None: task_as_dict["goal_id"] = self.goal_id - # if self.goal: - # task_as_dict["goal"] = self.goal.title return task_as_dict diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index da2a00e1b..b366bcc2f 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,7 +2,7 @@ from ..db import db from app.models.goal import Goal from app.models.task import Task -from .route_utilities import validate_model, get_models_with_filters, create_model +from .route_utilities import validate_model, create_model, get_models_by_order from datetime import datetime import os import requests @@ -12,47 +12,18 @@ @bp.post("") def create_goal(): request_body = request.get_json() - - try: - new_goal = Goal.from_dict(request_body) - except: - response = {"details": "Invalid data"} - abort(make_response(response, 400)) - - db.session.add(new_goal) - db.session.commit() - - #response = new_goal.to_dict() - response = {"id": new_goal.id, "title": new_goal.title} - - return response, 201 + return create_model(Goal, request_body) @bp.get("") def get_all_goals(): - query = db.select(Goal) - - sort_param = request.args.get('sort', None) - - if sort_param == "desc": - query = query.order_by(Goal.title.desc()) - elif sort_param == "asc": - query = query.order_by(Goal.title.asc()) - - goals = db.session.scalars(query) - - goals_response = [] - for goal in goals: - #goal_dict = goal.to_dict() - goal_dict = {"id": goal.id, "title": goal.title} - - goals_response.append(goal_dict) - return goals_response + return get_models_by_order(Goal) @bp.get("/") def get_one_goal(goal_id): goal = validate_model(Goal, goal_id) goal_dict = {"id": goal.id, "title": goal.title} - return goal_dict #goal.to_dict() + + return goal_dict @bp.put("/") def update_goal(goal_id): @@ -84,19 +55,14 @@ def creat_tasks_for_goal(goal_id): for task_id in task_id_list: task = validate_model(Task, task_id) task.goal = goal - db.session.commit() response = {"id": goal.id, "task_ids": task_id_list} return response, 200 - - @bp.get("//tasks") def get_tasks_for_one_goal(goal_id): goal = validate_model(Goal, goal_id) - response = goal.to_dict(include_goal_id_in_tasks = True) - #del response["task_ids"] - #response = goal.task.to_dict() + response = goal.to_dict(include_tasks = True, include_goal_id_in_tasks = True) return response \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 651ae1113..66503fec9 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,4 +1,4 @@ -from flask import abort, make_response, Response +from flask import abort, make_response, Response, request from ..db import db def validate_model(cls, model_id): @@ -17,18 +17,24 @@ def validate_model(cls, model_id): return model - -def get_models_with_filters(cls, filters=None): +def get_models_by_order(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)) - models_response = [model.to_dict() for model in models] - return models_response + + sort_param = request.args.get('sort', None) + + if sort_param == "desc": + query = query.order_by(cls.title.desc()) + elif sort_param == "asc": + query = query.order_by(cls.title.asc()) + + models = db.session.scalars(query) + + model_response = [] + for model in models: + model_dict = model.to_dict() + model_response.append(model_dict) + + return model_response def create_model(cls, model_data): try: diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 0ff28c66e..40e8e9272 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task -from .route_utilities import validate_model, get_models_with_filters +from .route_utilities import validate_model, create_model, get_models_by_order from datetime import datetime import os import requests @@ -11,38 +11,11 @@ @bp.post("") def create_task(): request_body = request.get_json() - - try: - new_task = Task.from_dict(request_body) - except: - response = {"details": "Invalid data"} - abort(make_response(response, 400)) - - db.session.add(new_task) - db.session.commit() - - response = new_task.to_dict() - - return response, 201 + return create_model(Task, request_body) @bp.get("") def get_all_tasks(): - query = db.select(Task) - - sort_param = request.args.get('sort', None) - - if sort_param == "desc": - query = query.order_by(Task.title.desc()) - elif sort_param == "asc": - query = query.order_by(Task.title.asc()) - - tasks = db.session.scalars(query) - - tasks_response = [] - for task in tasks: - task_dict = task.to_dict() - tasks_response.append(task_dict) - return tasks_response + return get_models_by_order(Task) @bp.get("") @@ -57,7 +30,6 @@ def update_task(task_id): task.title = request_body["title"] task.description = request_body["description"] - #task.completed_at = request_body["completed_at"] db.session.commit() return Response(status=204, mimetype="application/json") @@ -73,12 +45,9 @@ def delete_task(task_id): @bp.patch("//mark_complete") def patch_complete_task(task_id): - #Mark Complete on an Incomplete Task; Mark Complete on a Completed Task task = validate_model(Task, task_id) - task.completed_at = datetime.now() db.session.commit() - generate_slack_notification(task.title) return Response(status=204, mimetype="application/json") @@ -86,7 +55,6 @@ def patch_complete_task(task_id): @bp.patch("//mark_incomplete") def patch_incomplete_task(task_id): - #Mark Incomplete on a Completed Task; Mark Incomplete on an Incomplete Task task = validate_model(Task, task_id) task.completed_at = None @@ -107,15 +75,4 @@ def generate_slack_notification(model_attribute): "text": f"Someone just completed the task {model_attribute}" } - slack_response = requests.post(path, headers=headers, json=json) - - - -# Tasks should contain these attributes. The tests require the following columns to be named exactly as title, description, and completed_at. - -# id: a primary key for each task -# title: text to name the task -# description: text to describe the task -# completed_at: a datetime that represents the date that a task is completed on. Can be nullable, and contain a null value. A task with a null value for completed_at has not been completed. When we create a new task, completed_at should be null AKA None in Python. - - + slack_response = requests.post(path, headers=headers, json=json) \ No newline at end of file From b440789de3ec5189d2e5021ba0fb9b4010bcff63 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 18:36:47 -0800 Subject: [PATCH 16/17] refactor-2 --- app/models/task.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 17426890b..cff1479ea 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -27,13 +27,10 @@ def to_dict(self, include_goal_id = False): @classmethod def from_dict(cls, task_data): - goal_id = task_data.get("goal_id") new_task = cls(title = task_data["title"], description = task_data["description"], completed_at = None if ("is_complete" not in task_data or task_data["is_complete"] is False) - else cls.completed_at, - goal_id = goal_id) - + else cls.completed_at) return new_task From a612664ac37ad1ae404cb7b5de8fafff10ad4187 Mon Sep 17 00:00:00 2001 From: Esmeralda Arreguin-Martinez Date: Thu, 6 Nov 2025 19:16:11 -0800 Subject: [PATCH 17/17] refactor 3-moved slack def to utilities --- app/routes/route_utilities.py | 18 +++++++++++++++++- app/routes/task_routes.py | 18 ++---------------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 66503fec9..5357a8169 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,5 +1,7 @@ from flask import abort, make_response, Response, request from ..db import db +import os +import requests def validate_model(cls, model_id): try: @@ -47,4 +49,18 @@ def create_model(cls, model_data): db.session.add(new_model) db.session.commit() - return new_model.to_dict(), 201 \ No newline at end of file + return new_model.to_dict(), 201 + +def generate_slack_notification(model_attribute): + path = "https://slack.com/api/chat.postMessage" + SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") + + headers = { + "Authorization": f"Bearer {SLACK_TOKEN}" + } + json = { + "channel": "task-notifications", + "text": f"Someone just completed the task {model_attribute}" + } + + slack_response = requests.post(path, headers=headers, json=json) \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 40e8e9272..c34c9355d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,10 +1,9 @@ from flask import Blueprint, abort, make_response, request, Response from ..db import db from app.models.task import Task -from .route_utilities import validate_model, create_model, get_models_by_order +from .route_utilities import validate_model, create_model, get_models_by_order, generate_slack_notification from datetime import datetime -import os -import requests + bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -63,16 +62,3 @@ def patch_incomplete_task(task_id): return Response(status=204, mimetype="application/json") -def generate_slack_notification(model_attribute): - path = "https://slack.com/api/chat.postMessage" - SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") - - headers = { - "Authorization": f"Bearer {SLACK_TOKEN}" - } - json = { - "channel": "task-notifications", - "text": f"Someone just completed the task {model_attribute}" - } - - slack_response = requests.post(path, headers=headers, json=json) \ No newline at end of file