From 460806df6dfb61168967757d9e30be35926b7f01 Mon Sep 17 00:00:00 2001 From: Solhee Date: Thu, 8 May 2025 11:30:02 -0700 Subject: [PATCH 1/5] Wave 1 complete -- task endpoints implemented --- app/__init__.py | 2 + app/models/task.py | 31 ++++++++ app/routes/route_utilities.py | 48 ++++++++++++ app/routes/task_routes.py | 43 +++++++++- migrations/README | 1 + migrations/alembic.ini | 50 ++++++++++++ migrations/env.py | 113 +++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++ migrations/versions/6dba6251c8cf_.py | 39 +++++++++ tests/test_wave_01.py | 41 ++++------ 10 files changed, 364 insertions(+), 28 deletions(-) create mode 100644 app/routes/route_utilities.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/6dba6251c8cf_.py diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..eb060478c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from .db import db, migrate from .models import task, goal +from .routes.task_routes import bp as task_list_bp import os def create_app(config=None): @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(task_list_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..6eeeb55e8 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,36 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from datetime import datetime +from typing import Optional # dont HAVE to include this, could still be 'null' without it...? 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) + # completed_at represents the data a task is completed on -- can be nullable. null value = not completed yet. + # When a task is created, completed_at should be null (AKA None) + + @classmethod + def from_dict(cls, task_data): + completed_at = task_data.get("completed_at") # does this work..? + if completed_at: + is_complete = True + else: + is_complete = False + new_task = cls(title=task_data["title"], + description=task_data["description"], + # is_complete=completed_at is not None # ignore for now, default to null? + ) + + return new_task + + def to_dict(self): + task_as_dict = {} + task_as_dict["id"] = self.id + task_as_dict["title"] = self.title + task_as_dict["description"] = self.description + task_as_dict["is_complete"] = self.completed_at is not None # does this work? + # if self.completed_at: # so it's not null + # task_as_dict["completed_at"] = True + return task_as_dict \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..7d48a85e5 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,48 @@ +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 + +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]}"} + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_model) + db.session.commit() + + return {"task": new_model.to_dict()}, 201 # MAKE THIS UNIVERSAL LATER SO IT'S NOT TASK {to.lower(cls.__name__)}? + +def get_models_with_filters(cls, filters=None): + query = db.select(cls) + + # if "sort" in filters: # ASSUMING FOR NOW, THAT IF SORT IS THERE IT'S JUST SORT + # if filers["sort"] == "asc": + + if filters: # ASSUMING FOR NOW, THAT IF SORT IS THERE IT'S JUST SORT + # if "sort" in filters: + # sort = filters.remove("sort").value() + 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] # if we change the ^ one to remove "task", can do model.to_dict("task") here? + return models_response diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..3ad2a2f64 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,42 @@ -from flask import Blueprint \ No newline at end of file +from flask import abort, Blueprint, make_response, request, Response +from app.models.task import Task +from ..db import db +from .route_utilities import create_model, get_models_with_filters, validate_model + +bp = Blueprint("task_list_bp", __name__, url_prefix="/tasks") + +@bp.post("") +def create_task(): + request_body = request.get_json() + return create_model(Task, request_body) + +@bp.get("") +def get_all_tasks(): + return get_models_with_filters(Task, request.args) + +@bp.get("/") +def get_one_task(task_id): + task = validate_model(Task, task_id) + result = {} + result["task"] = task.to_dict() # RE-EVALUATE THIS LATER + return result + +@bp.put("/") +def update_task(task_id): + task = validate_model(Task, task_id) + request_body = request.get_json() + + task.title = request_body["title"] + task.description = request_body["description"] + + db.session.commit() + + return Response(status=204, mimetype="application/json") + +@bp.delete("/") +def delete_task(task_id): + task = validate_model(Task, task_id) + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype="application/json") \ No newline at end of file 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"} diff --git a/migrations/versions/6dba6251c8cf_.py b/migrations/versions/6dba6251c8cf_.py new file mode 100644 index 000000000..2e62be650 --- /dev/null +++ b/migrations/versions/6dba6251c8cf_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 6dba6251c8cf +Revises: +Create Date: 2025-05-01 13:40:27.118486 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6dba6251c8cf' +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..ce3ecce5f 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -3,7 +3,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -14,7 +14,7 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_one_saved_tasks(client, one_task): # Act response = client.get("/tasks") @@ -33,7 +33,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -52,7 +52,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -60,14 +60,10 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -97,7 +93,7 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -117,7 +113,7 @@ def test_update_task(client, one_task): -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -128,14 +124,10 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {"message": "Task 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -146,7 +138,7 @@ def test_delete_task(client, one_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query) == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -154,16 +146,11 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - + assert response_body == {"message": "Task 1 not found"} assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -180,7 +167,7 @@ def test_create_task_must_contain_title(client): assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ From c6509d9f33f57f35bf24df891b6a4070dbc48454 Mon Sep 17 00:00:00 2001 From: Solhee Date: Thu, 8 May 2025 13:39:36 -0700 Subject: [PATCH 2/5] Wave 2, 3 complete --- app/routes/route_utilities.py | 23 ++++++++++++----------- app/routes/task_routes.py | 18 ++++++++++++++++++ tests/test_wave_02.py | 4 ++-- tests/test_wave_03.py | 24 ++++++++---------------- 4 files changed, 40 insertions(+), 29 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 7d48a85e5..62e227a4b 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -32,17 +32,18 @@ def create_model(cls, model_data): def get_models_with_filters(cls, filters=None): query = db.select(cls) - - # if "sort" in filters: # ASSUMING FOR NOW, THAT IF SORT IS THERE IT'S JUST SORT - # if filers["sort"] == "asc": - - if filters: # ASSUMING FOR NOW, THAT IF SORT IS THERE IT'S JUST SORT - # if "sort" in filters: - # sort = filters.remove("sort").value() + filters = dict(filters) # is this okay? I think so + sort_order = filters.pop("sort", None) # defaults to none if not present -- assuming we want to sort by id if 'sort' isn't given + + 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] # if we change the ^ one to remove "task", can do model.to_dict("task") here? - return models_response + if sort_order == "desc": + sort_clause = cls.title.desc() + elif sort_order == "asc": + sort_clause = cls.title.asc() + else: + sort_clause = cls.id + models = db.session.scalars(query.order_by(sort_clause)) + return [model.to_dict() for model in models] # if we change the ^ one to remove "task", can do model.to_dict("task") here? diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3ad2a2f64..477d3639b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,6 +2,7 @@ from app.models.task import Task from ..db import db from .route_utilities import create_model, get_models_with_filters, validate_model +from datetime import datetime bp = Blueprint("task_list_bp", __name__, url_prefix="/tasks") @@ -39,4 +40,21 @@ def delete_task(task_id): db.session.delete(task) db.session.commit() + return Response(status=204, mimetype="application/json") + +# Wave 3 +@bp.patch("//mark_complete") +def mark_complete(task_id): + task = validate_model(Task, task_id) + task.completed_at = datetime.now() + db.session.commit() + + return Response(status=204, mimetype="application/json") + +@bp.patch("//mark_incomplete") +def mark_incomplete(task_id): + task = validate_model(Task, task_id) + task.completed_at = None + db.session.commit() + return Response(status=204, mimetype="application/json") \ No newline at end of file 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") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..f14c4bb1a 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,10 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -109,8 +105,4 @@ 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 response_body == {"message": "Task 1 not found"} From 372f83b3f4d568ea600eb68088da86bb1d59d8bb Mon Sep 17 00:00:00 2001 From: Solhee Date: Thu, 8 May 2025 22:18:38 -0700 Subject: [PATCH 3/5] Implemented wave 4 - connected to Slack API --- app/__init__.py | 3 +++ app/routes/slack_routes.py | 25 +++++++++++++++++++++++++ app/routes/task_routes.py | 3 +++ 3 files changed, 31 insertions(+) create mode 100644 app/routes/slack_routes.py diff --git a/app/__init__.py b/app/__init__.py index eb060478c..8365de018 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,3 +1,6 @@ +from dotenv import load_dotenv # loads .env variables into os.environ +load_dotenv() + from flask import Flask from .db import db, migrate from .models import task, goal diff --git a/app/routes/slack_routes.py b/app/routes/slack_routes.py new file mode 100644 index 000000000..01e2e5f0c --- /dev/null +++ b/app/routes/slack_routes.py @@ -0,0 +1,25 @@ +import os +from flask import abort, make_response +import requests + +SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN") +SLACK_API_URL = "https://slack.com/api/chat.postMessage" + +def send_slack_notification(message, channel="#task-notifications"): + headers = { + "Authorization": SLACK_BOT_TOKEN, + "Content-Type": "application/json" + } + + request_body = { + "channel": channel, + "text": message + } + + try: + response = requests.post(SLACK_API_URL, headers=headers, json=request_body) + + except: # for any exception + abort(make_response({"message": f"Slack API error"}, 400)) + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 477d3639b..e0310a487 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,6 +3,7 @@ from ..db import db from .route_utilities import create_model, get_models_with_filters, validate_model from datetime import datetime +from .slack_routes import send_slack_notification bp = Blueprint("task_list_bp", __name__, url_prefix="/tasks") @@ -49,6 +50,8 @@ def mark_complete(task_id): task.completed_at = datetime.now() db.session.commit() + send_slack_notification(f"Someone just completed the task {task.title}") + return Response(status=204, mimetype="application/json") @bp.patch("//mark_incomplete") From 3a81d4cf8a3bd9a3587ce938327dc9f7c09c91e2 Mon Sep 17 00:00:00 2001 From: Solhee Date: Sat, 10 May 2025 22:42:17 -0700 Subject: [PATCH 4/5] Completed wave 6 --- app/__init__.py | 2 + app/models/goal.py | 22 ++++++- app/models/task.py | 23 ++++--- app/routes/goal_routes.py | 89 +++++++++++++++++++++++++++- app/routes/route_utilities.py | 6 +- migrations/versions/9d332b124243_.py | 34 +++++++++++ migrations/versions/e624940a339e_.py | 32 ++++++++++ tests/test_wave_05.py | 77 ++++++++++++------------ tests/test_wave_06.py | 21 +++---- 9 files changed, 240 insertions(+), 66 deletions(-) create mode 100644 migrations/versions/9d332b124243_.py create mode 100644 migrations/versions/e624940a339e_.py diff --git a/app/__init__.py b/app/__init__.py index 8365de018..4a782c7df 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -5,6 +5,7 @@ from .db import db, migrate from .models import task, goal from .routes.task_routes import bp as task_list_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -23,5 +24,6 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(task_list_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..dfc53d3f8 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,25 @@ -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 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") + + @classmethod + def from_dict(cls, goal_data): + new_goal = cls(title=goal_data["title"]) + return new_goal + + def to_dict(self): + goal_as_dict = {} + goal_as_dict["id"] = self.id + goal_as_dict["title"] = self.title + + if self.tasks: # Shouldn't affect test prior to wave 6. + goal_as_dict["tasks"] = [task.to_dict() for task in self.tasks] + + return goal_as_dict \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 6eeeb55e8..14f32170f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,7 +1,10 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey +from typing import Optional, TYPE_CHECKING from ..db import db from datetime import datetime -from typing import Optional # dont HAVE to include this, could still be 'null' without it...? +if TYPE_CHECKING: + from .goal import Goal class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) @@ -9,18 +12,20 @@ class Task(db.Model): description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) # completed_at represents the data a task is completed on -- can be nullable. null value = not completed yet. - # When a task is created, completed_at should be null (AKA None) + # When a task is created, completed_at should be null (AKA None) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") @classmethod def from_dict(cls, task_data): - completed_at = task_data.get("completed_at") # does this work..? + completed_at = task_data.get("completed_at") if completed_at: is_complete = True else: is_complete = False new_task = cls(title=task_data["title"], description=task_data["description"], - # is_complete=completed_at is not None # ignore for now, default to null? + # completed_at=task_data["completed_at"] # will this be none if it's not there? ) return new_task @@ -30,7 +35,9 @@ def to_dict(self): task_as_dict["id"] = self.id task_as_dict["title"] = self.title task_as_dict["description"] = self.description - task_as_dict["is_complete"] = self.completed_at is not None # does this work? - # if self.completed_at: # so it's not null - # task_as_dict["completed_at"] = True + task_as_dict["is_complete"] = self.completed_at is not None + + if self.goal_id: + task_as_dict["goal_id"] = self.goal_id # Shouldn't affect previous tests + return task_as_dict \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..b4e68b9b3 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,88 @@ -from flask import Blueprint \ No newline at end of file +from flask import abort, Blueprint, make_response, request, Response +from app.models.goal import Goal +from app.models.task import Task +from ..db import db +from .route_utilities import create_model, get_models_with_filters, validate_model + +bp = Blueprint("goals_bp", __name__, url_prefix="/goals") + +@bp.post("") +def create_task(): + request_body = request.get_json() + return create_model(Goal, request_body) + +@bp.get("") +def get_all_goals(): + return get_models_with_filters(Goal, request.args) + +@bp.get("/") +def get_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + result = {} + result["goal"] = goal.to_dict() # RE-EVALUATE THIS LATER + return result + +@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): + goal = validate_model(Goal, goal_id) + db.session.delete(goal) + db.session.commit() + + return Response(status=204, mimetype="application/json") + +@bp.post("//tasks") +def connect_task_to_goal(goal_id): + + goal = validate_model(Goal, goal_id) + + # try: + # goal_id == goal.id + # except: + # response = {"message": f"Invalid request: ID given in path not equivalent to ID in request body."} + # abort(make_response(response, 400)) # CHECK THIS LATER WHAT RESPONSE CODE SHOULD I DO + + request_body = request.get_json() # this should be the dict w/ key: task_ids value: list of the ids + tasks = [] + + for task_id in request_body["task_ids"]: + task = validate_model(Task, task_id) + tasks.append(task) + # If any of the task IDs are invalid, will abort before this point. + # Assume we do not want to associate any of the tasks with the goal if *any* + # of the IDs are invalid. + + for task in goal.tasks: + # Unassociate previously associated tasks + task.goal_id = None + + for task in tasks: + task.goal_id = goal_id # only need to update FK in task item to create relationship + + db.session.commit() + + response_body = { + "id": goal.id, + "task_ids": request_body["task_ids"] # To reach this point, all the given IDs have been verified + relationship created. + } + return response_body, 200 # fix this later + +@bp.get("//tasks") +def get_tasks(goal_id): # getting tasks of one goal + goal = validate_model(Goal, goal_id) + response_body = goal.to_dict() + + if not goal.tasks: + response_body["tasks"] = [] # Do this to avoid issues with previous tests + + return response_body, 200 \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 62e227a4b..29965099c 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -28,11 +28,11 @@ def create_model(cls, model_data): db.session.add(new_model) db.session.commit() - return {"task": new_model.to_dict()}, 201 # MAKE THIS UNIVERSAL LATER SO IT'S NOT TASK {to.lower(cls.__name__)}? + return {cls.__name__.lower(): new_model.to_dict()}, 201 def get_models_with_filters(cls, filters=None): query = db.select(cls) - filters = dict(filters) # is this okay? I think so + filters = dict(filters) sort_order = filters.pop("sort", None) # defaults to none if not present -- assuming we want to sort by id if 'sort' isn't given if filters: @@ -46,4 +46,4 @@ def get_models_with_filters(cls, filters=None): else: sort_clause = cls.id models = db.session.scalars(query.order_by(sort_clause)) - return [model.to_dict() for model in models] # if we change the ^ one to remove "task", can do model.to_dict("task") here? + return [model.to_dict() for model in models] diff --git a/migrations/versions/9d332b124243_.py b/migrations/versions/9d332b124243_.py new file mode 100644 index 000000000..ddd4b9667 --- /dev/null +++ b/migrations/versions/9d332b124243_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 9d332b124243 +Revises: e624940a339e +Create Date: 2025-05-09 09:46:32.713484 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9d332b124243' +down_revision = 'e624940a339e' +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/migrations/versions/e624940a339e_.py b/migrations/versions/e624940a339e_.py new file mode 100644 index 000000000..7bd4396b3 --- /dev/null +++ b/migrations/versions/e624940a339e_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: e624940a339e +Revises: 6dba6251c8cf +Create Date: 2025-05-08 22:20:15.622831 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e624940a339e' +down_revision = '6dba6251c8cf' +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..7b2f9c1a8 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_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +13,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 +30,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +47,19 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,34 +78,39 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 204 + + query = db.select(Goal).where(Goal.id == 1) + goal = db.session.scalar(query) + + assert goal.title == "Updated Goal Title" + # DO I NEED TO ADD ANOTHER ASSERTION -- it said 3 -@pytest.mark.skip(reason="test to be completed by student") + +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -121,28 +124,22 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "message" in response_body - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- - + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} + assert db.session.scalars(db.select(Goal)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 0317f835a..8a6206daa 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,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") - # ***************************************************************** - # **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 +72,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,11 +97,11 @@ 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() - + assert response.status_code == 200 assert "task" in response_body assert "goal_id" in response_body["task"] From c5ab641dc1e7a2b9c9e90240915481855a3f41f9 Mon Sep 17 00:00:00 2001 From: Solhee Date: Sun, 11 May 2025 00:49:03 -0700 Subject: [PATCH 5/5] Completed Wave 6, cleaned up code and comments. --- app/models/task.py | 9 +-------- app/routes/goal_routes.py | 23 +++++++++-------------- app/routes/route_utilities.py | 4 ++-- app/routes/task_routes.py | 4 ++-- 4 files changed, 14 insertions(+), 26 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 14f32170f..bbbbd3f32 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,21 +11,14 @@ class Task(db.Model): title: Mapped[str] description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) - # completed_at represents the data a task is completed on -- can be nullable. null value = not completed yet. - # When a task is created, completed_at should be null (AKA None) goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") @classmethod def from_dict(cls, task_data): completed_at = task_data.get("completed_at") - if completed_at: - is_complete = True - else: - is_complete = False new_task = cls(title=task_data["title"], - description=task_data["description"], - # completed_at=task_data["completed_at"] # will this be none if it's not there? + description=task_data["description"] ) return new_task diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index b4e68b9b3..c9150aa93 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, make_response, request, Response +from flask import Blueprint, request, Response from app.models.goal import Goal from app.models.task import Task from ..db import db @@ -19,7 +19,7 @@ def get_all_goals(): def get_one_goal(goal_id): goal = validate_model(Goal, goal_id) result = {} - result["goal"] = goal.to_dict() # RE-EVALUATE THIS LATER + result["goal"] = goal.to_dict() return result @bp.put("/") @@ -46,13 +46,7 @@ def connect_task_to_goal(goal_id): goal = validate_model(Goal, goal_id) - # try: - # goal_id == goal.id - # except: - # response = {"message": f"Invalid request: ID given in path not equivalent to ID in request body."} - # abort(make_response(response, 400)) # CHECK THIS LATER WHAT RESPONSE CODE SHOULD I DO - - request_body = request.get_json() # this should be the dict w/ key: task_ids value: list of the ids + request_body = request.get_json() tasks = [] for task_id in request_body["task_ids"]: @@ -67,22 +61,23 @@ def connect_task_to_goal(goal_id): task.goal_id = None for task in tasks: - task.goal_id = goal_id # only need to update FK in task item to create relationship + task.goal_id = goal_id # only need to update FK in task to create relationship db.session.commit() + # To reach this point, all the given IDs have been verified + relationship created. response_body = { "id": goal.id, - "task_ids": request_body["task_ids"] # To reach this point, all the given IDs have been verified + relationship created. + "task_ids": request_body["task_ids"] } - return response_body, 200 # fix this later + return response_body, 200 @bp.get("//tasks") -def get_tasks(goal_id): # getting tasks of one goal +def get_tasks(goal_id): goal = validate_model(Goal, goal_id) response_body = goal.to_dict() if not goal.tasks: - response_body["tasks"] = [] # Do this to avoid issues with previous tests + response_body["tasks"] = [] # To avoid issues with previous tests return response_body, 200 \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 29965099c..78d5acb95 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -21,7 +21,6 @@ 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]}"} response = {"details": "Invalid data"} abort(make_response(response, 400)) @@ -33,7 +32,8 @@ def create_model(cls, model_data): def get_models_with_filters(cls, filters=None): query = db.select(cls) filters = dict(filters) - sort_order = filters.pop("sort", None) # defaults to none if not present -- assuming we want to sort by id if 'sort' isn't given + sort_order = filters.pop("sort", None) + # defaults to none if not present. Assuming we want to sort by id if 'sort' isn't given if filters: for attribute, value in filters.items(): diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e0310a487..38bb88688 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, make_response, request, Response +from flask import Blueprint, request, Response from app.models.task import Task from ..db import db from .route_utilities import create_model, get_models_with_filters, validate_model @@ -20,7 +20,7 @@ def get_all_tasks(): def get_one_task(task_id): task = validate_model(Task, task_id) result = {} - result["task"] = task.to_dict() # RE-EVALUATE THIS LATER + result["task"] = task.to_dict() return result @bp.put("/")