From a5d4ebbfe27f3767642d8aac81650c88ee6dafed Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Thu, 1 May 2025 14:07:16 -0700 Subject: [PATCH 1/9] set up project and generate migrations folder --- 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 ab24591a0bbca2e3d1eae4275db3ebacbae3ed40 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Mon, 5 May 2025 23:39:31 -0700 Subject: [PATCH 2/9] implemented wave 1 and passed all tests --- app/__init__.py | 2 + app/models/task.py | 26 +++++++ app/routes/route_utilities.py | 18 +++++ app/routes/task_routes.py | 74 ++++++++++++++++++- .../versions/43eaca8fd4c5_add_task_model.py | 39 ++++++++++ tests/test_wave_01.py | 56 +++++++------- 6 files changed, 189 insertions(+), 26 deletions(-) create mode 100644 app/routes/route_utilities.py create mode 100644 migrations/versions/43eaca8fd4c5_add_task_model.py diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..a356fed22 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,6 +2,7 @@ from .db import db, migrate from .models import task, goal import os +from .routes.task_routes import tasks_bp def create_app(config=None): app = Flask(__name__) @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(tasks_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..18860ca88 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,31 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from typing import Optional +from datetime import datetime +from flask import abort, make_response 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) + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": self.completed_at is not None + } + + @classmethod + def from_dict(cls, task_data): + # clean option for post create task + # if "title" not in task_data or "description" not in task_data: + # abort(make_response({"details": "Invalid data"}, 400)) + + return cls( + title=task_data["title"], + description=task_data["description"], + completed_at=task_data.get("completed_at") + ) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..bec81d1f9 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,18 @@ +from flask import abort, make_response +from ..db import db + +def validate_model(cls, id): + try: + id = int(id) + except ValueError: + response = {"details": f"{cls.__name__} {id} invalid"} + abort(make_response(response, 400)) + + query = db.select(cls).where(cls.id == id) + model = db.session.scalar(query) + + if not model: + response = {"details": f"{cls.__name__} {id} not found"} + abort(make_response(response, 404)) + + return model \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..372c4cfe9 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,73 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response, jsonify +from ..db import db +from app.models.task import Task +from .route_utilities import validate_model + +tasks_bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") + +# POST /tasks +@tasks_bp.post("") +def create_task(): + request_body = request.get_json() + + if "title" not in request_body or "description" not in request_body: + return {"details": "Invalid data"}, 400 + + task = Task.from_dict(request_body) + db.session.add(task) + db.session.commit() + + return jsonify({"task": task.to_dict()}), 201 + + +# GET /tasks +@tasks_bp.get("") +def get_all_tasks(): + query = db.select(Task) + + title_param = request.args.get("title") + if title_param: + query = query.where(Task.title.ilike(f"%{title_param}%")) + + description_param = request.args.get("description") + if description_param: + query = query.where(Task.description.ilike(f"%{description_param}%")) + + query = query.order_by(Task.title.desc()) + tasks = db.session.scalars(query) + + tasks_response = [] + for task in tasks: + tasks_response.append(task.to_dict()) + + return tasks_response + + +# GET /tasks/1 +@tasks_bp.get("/") +def get_one_task(id): + task = validate_model(Task, id) + return jsonify({"task": task.to_dict()}), 200 + + +# PUT /tasks/1 +@tasks_bp.put("/") +def update_task(id): + task = validate_model(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") + + +# DELETE /tasks/1 +@tasks_bp.delete("/") +def delete_task(id): + task = validate_model(Task, id) + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype="application/json") diff --git a/migrations/versions/43eaca8fd4c5_add_task_model.py b/migrations/versions/43eaca8fd4c5_add_task_model.py new file mode 100644 index 000000000..3f19a3c99 --- /dev/null +++ b/migrations/versions/43eaca8fd4c5_add_task_model.py @@ -0,0 +1,39 @@ +"""Add Task model + +Revision ID: 43eaca8fd4c5 +Revises: +Create Date: 2025-05-05 22:14:43.127298 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '43eaca8fd4c5' +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/tests/test_wave_01.py b/tests/test_wave_01.py index 55475db79..6e2e3f48b 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") @@ -51,8 +51,8 @@ def test_get_task(client, one_task): } } - -@pytest.mark.skip(reason="No way to test this feature yet") +# edited +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -61,13 +61,14 @@ def test_get_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*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert "details" in response_body + assert response_body == { + "details": "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_create_task(client): # Act response = client.post("/tasks", json={ @@ -97,7 +98,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={ @@ -116,8 +117,8 @@ def test_update_task(client, one_task): assert task.completed_at == None - -@pytest.mark.skip(reason="No way to test this feature yet") +# edited +# @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={ @@ -129,13 +130,15 @@ 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*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert "details" in response_body + assert response_body == { + "details": "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 +149,9 @@ 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") + +# edited +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -155,15 +160,16 @@ 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*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert "details" in response_body + assert response_body == { + "details": "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 +186,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 73651e40fb0476a131eefb5902f0ab4951dc162b Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Tue, 6 May 2025 01:51:55 -0700 Subject: [PATCH 3/9] implemented wave 2, passed all tests --- app/routes/task_routes.py | 2 +- tests/test_wave_02.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 372c4cfe9..94d2744f3 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -33,7 +33,7 @@ def get_all_tasks(): if description_param: query = query.where(Task.description.ilike(f"%{description_param}%")) - query = query.order_by(Task.title.desc()) + query = query.order_by(Task.title.asc()) tasks = db.session.scalars(query) tasks_response = [] 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 40b93adc92115575dcd0d03d8fa780e9e6f274e9 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Tue, 6 May 2025 21:51:34 -0700 Subject: [PATCH 4/9] implemented wave 3, all tests passed --- app/__init__.py | 2 +- app/models/task.py | 2 +- app/routes/task_routes.py | 49 ++++++++++++++++++++++++++++++--------- tests/test_wave_03.py | 31 ++++++++++++------------- 4 files changed, 55 insertions(+), 29 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index a356fed22..9f9efb97f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,7 +2,7 @@ from .db import db, migrate from .models import task, goal import os -from .routes.task_routes import tasks_bp +from .routes.task_routes import bp as tasks_bp def create_app(config=None): app = Flask(__name__) diff --git a/app/models/task.py b/app/models/task.py index 18860ca88..3445eaf68 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -15,7 +15,7 @@ def to_dict(self): "id": self.id, "title": self.title, "description": self.description, - "is_complete": self.completed_at is not None + "is_complete": self.completed_at is not None #bool(self.completed_at) } @classmethod diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 94d2744f3..53364eb34 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,11 +2,12 @@ from ..db import db from app.models.task import Task from .route_utilities import validate_model +from datetime import datetime -tasks_bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") # POST /tasks -@tasks_bp.post("") +@bp.post("") def create_task(): request_body = request.get_json() @@ -21,7 +22,7 @@ def create_task(): # GET /tasks -@tasks_bp.get("") +@bp.get("") def get_all_tasks(): query = db.select(Task) @@ -33,25 +34,31 @@ def get_all_tasks(): if description_param: query = query.where(Task.description.ilike(f"%{description_param}%")) - query = query.order_by(Task.title.asc()) + sort_param = request.args.get("sort") + if sort_param == "desc": + query = query.order_by(Task.title.desc()) + else: + query = query.order_by(Task.title.asc()) + tasks = db.session.scalars(query) - tasks_response = [] - for task in tasks: - tasks_response.append(task.to_dict()) + # tasks_response = [] + # for task in tasks: + # tasks_response.append(task.to_dict()) - return tasks_response + # return tasks_response + return [task.to_dict() for task in tasks] # GET /tasks/1 -@tasks_bp.get("/") +@bp.get("/") def get_one_task(id): task = validate_model(Task, id) return jsonify({"task": task.to_dict()}), 200 # PUT /tasks/1 -@tasks_bp.put("/") +@bp.put("/") def update_task(id): task = validate_model(Task, id) request_body = request.get_json() @@ -64,10 +71,30 @@ def update_task(id): # DELETE /tasks/1 -@tasks_bp.delete("/") +@bp.delete("/") def delete_task(id): task = validate_model(Task, id) db.session.delete(task) db.session.commit() return Response(status=204, mimetype="application/json") + + +# PATCH /tasks/1/mark_complete +@bp.patch("//mark_complete") +def mark_complete(id): + task = validate_model(Task, id) + task.completed_at = datetime.now() + db.session.commit() + + return Response(status=204, mimetype="application/json") + + +# PATCH /tasks/1/mark_incomplete +@bp.patch("//mark_incomplete") +def mark_incomplete(id): + task = validate_model(Task, id) + task.completed_at = None + db.session.commit() + + return Response(status=204, mimetype="application/json") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..9addfae85 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,13 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + + assert "details" in response_body + assert response_body == { + "details": "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") @@ -110,7 +109,7 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert "details" in response_body + assert response_body == { + "details": "Task 1 not found" + } \ No newline at end of file From ab7c074702598a94f425b6f56649306dde4c2858 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Wed, 7 May 2025 00:06:54 -0700 Subject: [PATCH 5/9] implemented wave 4: integrated slack api task bot --- app/routes/task_routes.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 53364eb34..89b7da8a7 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 from datetime import datetime +import requests, os + bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @@ -81,11 +83,27 @@ def delete_task(id): # PATCH /tasks/1/mark_complete +# Slack API @bp.patch("//mark_complete") def mark_complete(id): task = validate_model(Task, id) - task.completed_at = datetime.now() - db.session.commit() + if task.completed_at is None: + task.completed_at = datetime.now() + db.session.commit() + + slack_bot_token = os.environ.get("SLACK_BOT_TOKEN") + slack_channel = os.environ.get("SLACK_CHANNEL", "task-notifications") + + headers = { + "Authorization": f"Bearer {slack_bot_token}" + } + + payload = { + "channel": slack_channel, + "text": f"Someone just completed the task {task.title}" + } + + requests.post("https://slack.com/api/chat.postMessage", headers=headers, json=payload) return Response(status=204, mimetype="application/json") From 199c1186ec856e1aeb0ed88bab8d331c1167193e Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Thu, 8 May 2025 01:09:41 -0700 Subject: [PATCH 6/9] implemented wave 5: created second model - goal, crud, db migrate goal model, added tests, passed tests --- app/__init__.py | 2 + app/models/goal.py | 13 ++++ app/models/task.py | 6 +- app/routes/goal_routes.py | 67 ++++++++++++++++- migrations/versions/fcb217b372dc_.py | 32 ++++++++ tests/test_wave_05.py | 108 ++++++++++++++++----------- 6 files changed, 180 insertions(+), 48 deletions(-) create mode 100644 migrations/versions/fcb217b372dc_.py diff --git a/app/__init__.py b/app/__init__.py index 9f9efb97f..c89f6eb39 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,6 +3,7 @@ from .models import task, goal import os from .routes.task_routes import bp as tasks_bp +from .routes.goal_routes import bp as goals_bp def create_app(config=None): app = Flask(__name__) @@ -20,5 +21,6 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..a63e031bd 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,16 @@ 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): + return cls( + title=goal_data["title"] + ) \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 3445eaf68..53437be6e 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -2,7 +2,7 @@ from ..db import db from typing import Optional from datetime import datetime -from flask import abort, make_response +# from flask import abort, make_response class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) @@ -20,10 +20,6 @@ def to_dict(self): @classmethod def from_dict(cls, task_data): - # clean option for post create task - # if "title" not in task_data or "description" not in task_data: - # abort(make_response({"details": "Invalid data"}, 400)) - return cls( title=task_data["title"], description=task_data["description"], diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..b1b810c57 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,66 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response, jsonify +from ..db import db +from app.models.goal import Goal +from .route_utilities import validate_model +# import requests, os + +bp = Blueprint("goals_bp", __name__, url_prefix="/goals") + +# POST request to /goals +# invalid request is {} --> 400 +@bp.post("") +def create_goal(): + request_body = request.get_json() + + if "title" not in request_body: + return {"details": "Invalid data"}, 400 + + goal = Goal.from_dict(request_body) + db.session.add(goal) + db.session.commit() + + return jsonify({"goal": goal.to_dict()}), 201 + + +# GET request to /goals +# GET request to /goals 0 saved goals --> response 200 ok [] +@bp.get("") +def get_all_goals(): + query = db.select(Goal) + + title_param = request.args.get("title") + if title_param: + query = query.where(Goal.title.ilike(f"%{title_param}%")) + + goals = db.session.scalars(query) + + return [goal.to_dict() for goal in goals] + + +# GET request to /goals/1 +@bp.get("/") +def get_one_goal(id): + goal = validate_model(Goal, id) + return jsonify({"goal": goal.to_dict()}), 200 + + +# PUT request to /goals/1 +@bp.put("") +def update_goal(id): + goal = validate_model(Goal, id) + request_body = request.get_json() + + goal.title = request_body["title"] + + db.session.commit() + return Response(status=204, mimetype="application/json") + + +# DELETE request to /goals/1 +@bp.delete("") +def delete_goal(id): + goal = validate_model(Goal, id) + db.session.delete(goal) + db.session.commit() + + return Response(status=204, mimetype="application/json") diff --git a/migrations/versions/fcb217b372dc_.py b/migrations/versions/fcb217b372dc_.py new file mode 100644 index 000000000..0173857c3 --- /dev/null +++ b/migrations/versions/fcb217b372dc_.py @@ -0,0 +1,32 @@ +"""Add Goal Model + +Revision ID: fcb217b372dc +Revises: 43eaca8fd4c5 +Create Date: 2025-05-08 00:46:26.486497 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fcb217b372dc' +down_revision = '43eaca8fd4c5' +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 ### diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 222d10cf0..d85e7f3ed 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,9 @@ +from app.db import db +from app.models.goal import Goal 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") @@ -45,23 +47,26 @@ def test_get_goal(client, one_goal): } } - -@pytest.mark.skip(reason="test to be completed by student") +# edited +# @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 - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + + assert "details" in response_body + assert response_body == { + "details": "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 +85,47 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +# edited +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") + # 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") +# edited +# @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 Task 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 "details" in response_body + assert response_body == { + "details": "Goal 1 not found" + } -@pytest.mark.skip(reason="No way to test this feature yet") +# edited +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -120,29 +138,35 @@ def test_delete_goal(client, one_goal): assert response.status_code == 404 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 "details" in response_body + # raise Exception("Complete test with assertion about response body") + assert response_body == { + "details": "Goal 1 not found" + } -@pytest.mark.skip(reason="test to be completed by student") +# edited +# @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 - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + + # raise Exception("Complete test with assertion about response body") + assert "details" in response_body + assert response_body == { + "details": "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 e071c4ae461f4a06bebac934c8a6f60b47f52881 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Thu, 8 May 2025 16:26:05 -0700 Subject: [PATCH 7/9] implemented wave 6: created one to many relationship between goals and tasks, db migrate, passed all tests. --- app/models/goal.py | 10 +++- app/models/task.py | 17 ++++-- app/routes/goal_routes.py | 54 ++++++++++++++++++- app/routes/route_utilities.py | 15 +++++- ...reated_relationship_with_goal_model_to_.py | 34 ++++++++++++ tests/test_wave_06.py | 20 +++---- 6 files changed, 132 insertions(+), 18 deletions(-) create mode 100644 migrations/versions/a81e1af5bad6_created_relationship_with_goal_model_to_.py diff --git a/app/models/goal.py b/app/models/goal.py index a63e031bd..50e02ed7c 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,9 +1,14 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .task import Task +# PARENT 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 { @@ -14,5 +19,6 @@ def to_dict(self): @classmethod def from_dict(cls, goal_data): return cls( - title=goal_data["title"] + title=goal_data["title"], + tasks=goal_data.get("tasks", []) #new ) \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 53437be6e..a2ccc15eb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,21 +1,29 @@ -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 datetime import datetime -# from flask import abort, make_response +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .goal import Goal +# CHILD - FK 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") def to_dict(self): return { "id": self.id, "title": self.title, "description": self.description, - "is_complete": self.completed_at is not None #bool(self.completed_at) + "is_complete": self.completed_at is not None, + #"goal_id": self.goal_id + **({"goal_id": self.goal_id} if self.goal_id is not None else {}) } @classmethod @@ -23,5 +31,6 @@ def from_dict(cls, task_data): return cls( title=task_data["title"], description=task_data["description"], - completed_at=task_data.get("completed_at") + completed_at=task_data.get("completed_at"), + goal_id=task_data.get("goal_id") #new ) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index b1b810c57..6fb1a55ab 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,8 +1,8 @@ from flask import Blueprint, request, Response, jsonify from ..db import db from app.models.goal import Goal +from app.models.task import Task from .route_utilities import validate_model -# import requests, os bp = Blueprint("goals_bp", __name__, url_prefix="/goals") @@ -64,3 +64,55 @@ def delete_goal(id): db.session.commit() return Response(status=204, mimetype="application/json") + + +# nested routes +# POST /goals/1/tasks +@bp.post("//tasks") +def create_task_for_goal(id): + goal = validate_model(Goal, id) + request_body = request.get_json() + + # task_data = { + # "title": request_body["title"], + # "description": request_body["description"], + # "completed_at": request_body["completed_at"], + # "goal_id": goal.id + # } + + # return create_model(Task, task_data) + + + + task_ids = request_body.get("task_ids", []) + + # disassociate all current tasks + for task in goal.tasks: + task.goal_id = None + + # associate new tasks + for task_id in task_ids: + task = validate_model(Task, task_id) + task.goal_id = goal.id + + db.session.commit() + + return { + "id": goal.id, + "task_ids": task_ids + }, 200 + + +# GET /goals/333/tasks +# no matching tasks --> 200 ok [] +# no matching goal --> 404 +@bp.get("//tasks") +def get_tasks_for_goal(id): + # goal = validate_model(Goal, id) + # tasks = [task.to_dict() for task in goal.tasks] + # return tasks, 200 + + goal = validate_model(Goal, id) + goal_dict = goal.to_dict() + goal_dict["tasks"] = [task.to_dict() for task in goal.tasks] + return goal_dict, 200 \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index bec81d1f9..7cb67c8d2 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -15,4 +15,17 @@ def validate_model(cls, id): response = {"details": f"{cls.__name__} {id} not found"} abort(make_response(response, 404)) - return model \ No newline at end of file + return model + +# # create new instance of model from model_data +# def create_model(cls, model_data): +# try: +# new_model = cls.from_dict(model_data) +# except KeyError as e: +# response = {"details": f"Invalid data: missing {e.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/a81e1af5bad6_created_relationship_with_goal_model_to_.py b/migrations/versions/a81e1af5bad6_created_relationship_with_goal_model_to_.py new file mode 100644 index 000000000..2e29f6ad1 --- /dev/null +++ b/migrations/versions/a81e1af5bad6_created_relationship_with_goal_model_to_.py @@ -0,0 +1,34 @@ +"""created relationship with goal model to task model + +Revision ID: a81e1af5bad6 +Revises: fcb217b372dc +Create Date: 2025-05-08 15:34:20.615066 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a81e1af5bad6' +down_revision = 'fcb217b372dc' +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 ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 0317f835a..6f6c04784 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,14 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert "details" in response_body + assert response_body == { + "details": "Goal 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_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 2b0cf4b4ecf956225f2821f07cf876563ed7ba13 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Fri, 9 May 2025 01:04:30 -0700 Subject: [PATCH 8/9] refactor route helpers; added create_model; deleted comments --- app/models/goal.py | 2 +- app/models/task.py | 5 ++-- app/routes/goal_routes.py | 43 ++++------------------------------- app/routes/route_utilities.py | 20 ++++++++-------- app/routes/task_routes.py | 27 ++++------------------ tests/test_wave_01.py | 10 +------- tests/test_wave_05.py | 15 ++---------- 7 files changed, 24 insertions(+), 98 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 50e02ed7c..b0e08e160 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,7 +4,7 @@ if TYPE_CHECKING: from .task import Task -# PARENT + class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] diff --git a/app/models/task.py b/app/models/task.py index a2ccc15eb..a76526199 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: from .goal import Goal -# CHILD - FK + class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] @@ -22,7 +22,6 @@ def to_dict(self): "title": self.title, "description": self.description, "is_complete": self.completed_at is not None, - #"goal_id": self.goal_id **({"goal_id": self.goal_id} if self.goal_id is not None else {}) } @@ -32,5 +31,5 @@ def from_dict(cls, task_data): title=task_data["title"], description=task_data["description"], completed_at=task_data.get("completed_at"), - goal_id=task_data.get("goal_id") #new + goal_id=task_data.get("goal_id") ) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 6fb1a55ab..32d627540 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,28 +2,18 @@ from ..db import db from app.models.goal import Goal from app.models.task import Task -from .route_utilities import validate_model +from .route_utilities import validate_model, create_model bp = Blueprint("goals_bp", __name__, url_prefix="/goals") -# POST request to /goals -# invalid request is {} --> 400 + @bp.post("") def create_goal(): request_body = request.get_json() + goal_data, status_code = create_model(Goal, request_body) + return jsonify({"goal": goal_data}), status_code - if "title" not in request_body: - return {"details": "Invalid data"}, 400 - - goal = Goal.from_dict(request_body) - db.session.add(goal) - db.session.commit() - - return jsonify({"goal": goal.to_dict()}), 201 - -# GET request to /goals -# GET request to /goals 0 saved goals --> response 200 ok [] @bp.get("") def get_all_goals(): query = db.select(Goal) @@ -37,14 +27,12 @@ def get_all_goals(): return [goal.to_dict() for goal in goals] -# GET request to /goals/1 @bp.get("/") def get_one_goal(id): goal = validate_model(Goal, id) return jsonify({"goal": goal.to_dict()}), 200 -# PUT request to /goals/1 @bp.put("") def update_goal(id): goal = validate_model(Goal, id) @@ -56,7 +44,6 @@ def update_goal(id): return Response(status=204, mimetype="application/json") -# DELETE request to /goals/1 @bp.delete("") def delete_goal(id): goal = validate_model(Goal, id) @@ -66,31 +53,16 @@ def delete_goal(id): return Response(status=204, mimetype="application/json") -# nested routes -# POST /goals/1/tasks @bp.post("//tasks") def create_task_for_goal(id): goal = validate_model(Goal, id) request_body = request.get_json() - # task_data = { - # "title": request_body["title"], - # "description": request_body["description"], - # "completed_at": request_body["completed_at"], - # "goal_id": goal.id - # } - - # return create_model(Task, task_data) - - - task_ids = request_body.get("task_ids", []) - # disassociate all current tasks for task in goal.tasks: task.goal_id = None - # associate new tasks for task_id in task_ids: task = validate_model(Task, task_id) task.goal_id = goal.id @@ -103,15 +75,8 @@ def create_task_for_goal(id): }, 200 -# GET /goals/333/tasks -# no matching tasks --> 200 ok [] -# no matching goal --> 404 @bp.get("//tasks") def get_tasks_for_goal(id): - # goal = validate_model(Goal, id) - # tasks = [task.to_dict() for task in goal.tasks] - # return tasks, 200 - goal = validate_model(Goal, id) goal_dict = goal.to_dict() goal_dict["tasks"] = [task.to_dict() for task in goal.tasks] diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 7cb67c8d2..c1662c46c 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -17,15 +17,15 @@ def validate_model(cls, id): return model -# # create new instance of model from model_data -# def create_model(cls, model_data): -# try: -# new_model = cls.from_dict(model_data) -# except KeyError as e: -# response = {"details": f"Invalid data: missing {e.args[0]}"} -# abort(make_response(response, 400)) + +def create_model(cls, model_data): + try: + new_model = cls.from_dict(model_data) + except KeyError as e: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) -# db.session.add(new_model) -# db.session.commit() + 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 \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 89b7da8a7..92bca2908 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,29 +1,21 @@ from flask import Blueprint, request, Response, jsonify from ..db import db from app.models.task import Task -from .route_utilities import validate_model +from .route_utilities import validate_model, create_model from datetime import datetime import requests, os bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") -# POST /tasks + @bp.post("") def create_task(): request_body = request.get_json() + task_data, status_code = create_model(Task, request_body) + return jsonify({"task": task_data}), status_code - if "title" not in request_body or "description" not in request_body: - return {"details": "Invalid data"}, 400 - - task = Task.from_dict(request_body) - db.session.add(task) - db.session.commit() - - return jsonify({"task": task.to_dict()}), 201 - -# GET /tasks @bp.get("") def get_all_tasks(): query = db.select(Task) @@ -44,22 +36,15 @@ def get_all_tasks(): tasks = db.session.scalars(query) - # tasks_response = [] - # for task in tasks: - # tasks_response.append(task.to_dict()) - - # return tasks_response return [task.to_dict() for task in tasks] -# GET /tasks/1 @bp.get("/") def get_one_task(id): task = validate_model(Task, id) return jsonify({"task": task.to_dict()}), 200 -# PUT /tasks/1 @bp.put("/") def update_task(id): task = validate_model(Task, id) @@ -72,7 +57,6 @@ def update_task(id): return Response(status=204, mimetype="application/json") -# DELETE /tasks/1 @bp.delete("/") def delete_task(id): task = validate_model(Task, id) @@ -82,8 +66,6 @@ def delete_task(id): return Response(status=204, mimetype="application/json") -# PATCH /tasks/1/mark_complete -# Slack API @bp.patch("//mark_complete") def mark_complete(id): task = validate_model(Task, id) @@ -108,7 +90,6 @@ def mark_complete(id): return Response(status=204, mimetype="application/json") -# PATCH /tasks/1/mark_incomplete @bp.patch("//mark_incomplete") def mark_incomplete(id): task = validate_model(Task, id) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 6e2e3f48b..097ae80fe 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -51,7 +51,7 @@ def test_get_task(client, one_task): } } -# edited + # @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act @@ -60,8 +60,6 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - - # raise Exception("Complete test with assertion about response body") assert "details" in response_body assert response_body == { "details": "Task 1 not found" @@ -117,7 +115,6 @@ def test_update_task(client, one_task): assert task.completed_at == None -# edited # @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act @@ -129,8 +126,6 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - # raise Exception("Complete test with assertion about response body") assert "details" in response_body assert response_body == { "details": "Task 1 not found" @@ -150,7 +145,6 @@ def test_delete_task(client, one_task): assert db.session.scalar(query) == None -# edited # @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act @@ -159,8 +153,6 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - # raise Exception("Complete test with assertion about response body") assert "details" in response_body assert response_body == { "details": "Task 1 not found" diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index d85e7f3ed..e9a3a414a 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -47,18 +47,15 @@ def test_get_goal(client, one_goal): } } -# edited + # @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): # Act response = client.get("/goals/1") response_body = response.get_json() - # raise Exception("Complete test") - # Assert assert response.status_code == 404 - assert "details" in response_body assert response_body == { "details": "Goal 1 not found" @@ -85,7 +82,6 @@ def test_create_goal(client): } -# edited # @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): # raise Exception("Complete test") @@ -104,7 +100,6 @@ def test_update_goal(client, one_goal): assert goal.title == "Updated Goal Title" -# edited # @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): #raise Exception("Complete test") @@ -117,14 +112,12 @@ def test_update_goal_not_found(client): # Assert assert response.status_code == 404 - assert "details" in response_body assert response_body == { "details": "Goal 1 not found" } -# edited # @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act @@ -139,13 +132,11 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "details" in response_body - - # raise Exception("Complete test with assertion about response body") assert response_body == { "details": "Goal 1 not found" } -# edited + # @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): # raise Exception("Complete test") @@ -156,8 +147,6 @@ def test_delete_goal_not_found(client): # Assert assert response.status_code == 404 - - # raise Exception("Complete test with assertion about response body") assert "details" in response_body assert response_body == { "details": "Goal 1 not found" From 9335735f5604722b566192260354d75e8ed39652 Mon Sep 17 00:00:00 2001 From: Mikaela Baluyot Date: Fri, 9 May 2025 01:07:07 -0700 Subject: [PATCH 9/9] deleted comment --- app/models/goal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/goal.py b/app/models/goal.py index b0e08e160..8e2045eb1 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -20,5 +20,5 @@ def to_dict(self): def from_dict(cls, goal_data): return cls( title=goal_data["title"], - tasks=goal_data.get("tasks", []) #new + tasks=goal_data.get("tasks", []) ) \ No newline at end of file