From cd51c9e96dcd8a16a5b7405bd19b126b41c81785 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 14:03:47 -0700 Subject: [PATCH 01/26] add goal model --- app/models/goal.py | 6 ++ migrations/README | 1 + migrations/alembic.ini | 50 +++++++++++++++++ migrations/env.py | 113 ++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++ 5 files changed, 194 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/app/models/goal.py b/app/models/goal.py index 44282656b..2f56281ad 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,11 @@ +from datetime import datetime +from sqlalchemy import DateTime + + from sqlalchemy.orm import Mapped, mapped_column from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + datetime: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) 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 4fe118055d1668f254f24636f22a754afd8cddc0 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 18:11:45 -0700 Subject: [PATCH 02/26] add task model --- app/models/goal.py | 6 ------ app/models/task.py | 5 +++++ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 2f56281ad..44282656b 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,11 +1,5 @@ -from datetime import datetime -from sqlalchemy import DateTime - - from sqlalchemy.orm import Mapped, mapped_column from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - title: Mapped[str] - datetime: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..1edd886d4 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,10 @@ from sqlalchemy.orm import Mapped, mapped_column +from datetime import datetime from ..db import db class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + description: Mapped[str] + completed_at: Mapped[datetime] = mapped_column(nullable=True) + From 8d73e738406ac2d9cc9460fd1f3ad190bbc75d6c Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 18:29:15 -0700 Subject: [PATCH 03/26] add to_dict and from_dict methods to task model --- app/models/task.py | 11 ++++++++ migrations/versions/8269bc9c305b_.py | 39 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 migrations/versions/8269bc9c305b_.py diff --git a/app/models/task.py b/app/models/task.py index 1edd886d4..4a9c8533a 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,3 +8,14 @@ class Task(db.Model): description: Mapped[str] completed_at: Mapped[datetime] = mapped_column(nullable=True) + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "description": self.description, + "completed_at": self.completed_at + } + + @classmethod + def from_dict(cls, dict_data): + return cls(title=dict_data["title"], description=dict_data["description"], completed_at=dict_data["completed_at"]]) \ No newline at end of file diff --git a/migrations/versions/8269bc9c305b_.py b/migrations/versions/8269bc9c305b_.py new file mode 100644 index 000000000..4ffbe850c --- /dev/null +++ b/migrations/versions/8269bc9c305b_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 8269bc9c305b +Revises: +Create Date: 2025-05-01 18:13:34.013500 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8269bc9c305b' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### From 9e6a054ca3b64b819c46294f2ff5087401e999e0 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 18:51:22 -0700 Subject: [PATCH 04/26] add retrieve_model_instance_by_id --- app/models/task.py | 2 +- app/routes/helper_utilities.py | 18 ++++++++++++++++ migrations/versions/c62b77d928bc_.py | 31 ++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 app/routes/helper_utilities.py create mode 100644 migrations/versions/c62b77d928bc_.py diff --git a/app/models/task.py b/app/models/task.py index 4a9c8533a..a03c92292 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -18,4 +18,4 @@ def to_dict(self): @classmethod def from_dict(cls, dict_data): - return cls(title=dict_data["title"], description=dict_data["description"], completed_at=dict_data["completed_at"]]) \ No newline at end of file + return cls(title=dict_data["title"], description=dict_data["description"], completed_at=dict_data["completed_at"]) \ No newline at end of file diff --git a/app/routes/helper_utilities.py b/app/routes/helper_utilities.py new file mode 100644 index 000000000..a1c60b27b --- /dev/null +++ b/app/routes/helper_utilities.py @@ -0,0 +1,18 @@ +from flask import abort, make_response +from app.db import db + +def retrieve_model_instance_by_id(cls, model_id): + try: + model_id = int(model_id) + except: + response_message = {"message": f"{cls.__name__} id <{model_id}> is invalid."} + abort(make_response(response_message, 400)) + + query = db.select(cls).where(cls.id == model_id) + model = db.session.scalar(query) + + if not model: + response_message = {"message": f"{cls.__name__} with id <{model_id}> is not found."} + abort(make_response(response_message, 404)) + + return model diff --git a/migrations/versions/c62b77d928bc_.py b/migrations/versions/c62b77d928bc_.py new file mode 100644 index 000000000..c23815ef3 --- /dev/null +++ b/migrations/versions/c62b77d928bc_.py @@ -0,0 +1,31 @@ +"""empty message + +Revision ID: c62b77d928bc +Revises: 8269bc9c305b +Create Date: 2025-05-01 18:30:25.278797 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c62b77d928bc' +down_revision = '8269bc9c305b' +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') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('goal') + # ### end Alembic commands ### From 4a5bd48f9d5a5f6bdf0461cd6d865bb4b28657d5 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 19:07:53 -0700 Subject: [PATCH 05/26] add create_model_inst_from_dict_with_response --- .../{helper_utilities.py => routes_helper_utilities.py} | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) rename app/routes/{helper_utilities.py => routes_helper_utilities.py} (66%) diff --git a/app/routes/helper_utilities.py b/app/routes/routes_helper_utilities.py similarity index 66% rename from app/routes/helper_utilities.py rename to app/routes/routes_helper_utilities.py index a1c60b27b..b778a3477 100644 --- a/app/routes/helper_utilities.py +++ b/app/routes/routes_helper_utilities.py @@ -1,7 +1,7 @@ from flask import abort, make_response from app.db import db -def retrieve_model_instance_by_id(cls, model_id): +def retrieve_model_inst_by_id(cls, model_id): try: model_id = int(model_id) except: @@ -16,3 +16,10 @@ def retrieve_model_instance_by_id(cls, model_id): abort(make_response(response_message, 404)) return model + +def create_model_inst_from_dict_with_response(cls, inst_data): + new_instance = cls.from_dict(inst_data) + db.session.add(new_instance) + db.session.commit() + response = new_instance.to_dict() + return response, 201 From b3c7ea216c01fcd49e4c15df8f501499c3e2251d Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 19:27:44 -0700 Subject: [PATCH 06/26] add create_task, get_all_tasks --- app/routes/task_routes.py | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..3ba24d294 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,34 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request +from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response +from app.models.task import Task + +bp = Blueprint("task_bp", __name__, url_prefix="/tasks") + +# CREATE ONE TASK +@bp.post("") +def create_task(): + request_body = request.get_json() + return create_model_inst_from_dict_with_response(Task, request_body) + +# READ ALL TASKS +@bp.get("") +def get_all_tasks(): + query = db.select(Task).order_by(id) + tasks = db.session.scalars(query) + + response = [] + for task in tasks: + response.append(task.to_dict()) + + return response + + +# READ ONE TASK BY ID + +# UPDATE ONE TASK + +# PATCH ONE TASK + +# DELETE ONE TASK + +# DELETE ALL TASKS \ No newline at end of file From c458c796150f8dfc173655def3e8df56d3e8aaca Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 19:34:15 -0700 Subject: [PATCH 07/26] add get_task_by_id route --- app/routes/task_routes.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3ba24d294..4401a7436 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,5 +1,5 @@ from flask import Blueprint, request -from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response +from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -22,8 +22,12 @@ def get_all_tasks(): return response - # READ ONE TASK BY ID +@bp.get("/") +def get_task_by_id(task_id): + task = retrieve_model_inst_by_id(Task, task_id) + + return task.to_dict() # UPDATE ONE TASK From 4297d4a004ea5a2c06bd6dccc19e71ceba189159 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 19:44:02 -0700 Subject: [PATCH 08/26] add update_by_id endpoint --- app/routes/task_routes.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 4401a7436..ee9a3eae3 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -30,6 +30,20 @@ def get_task_by_id(task_id): return task.to_dict() # UPDATE ONE TASK +@bp.update("/") +def update_by_id(task_id): + task = retrieve_model_inst_by_id(Task, task_id) + request_body = request.get_json() + + + task.title = request_body["title"] + task.description = request_body["description"] + task.completed_at = request_body["completed_at"] + + db.session.commit() + + return Response(status=204, mimetype="application/json") + # PATCH ONE TASK From 33692114e30ae9ebbabe64705ee8617b8feb6175 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 19:48:19 -0700 Subject: [PATCH 09/26] add delete_by_id endpoint --- app/routes/task_routes.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ee9a3eae3..6ea7728c1 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -48,5 +48,13 @@ def update_by_id(task_id): # PATCH ONE TASK # DELETE ONE TASK +@bp.delete("/ Date: Thu, 1 May 2025 19:58:05 -0700 Subject: [PATCH 10/26] add delete all tasks endpoint --- app/routes/task_routes.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 6ea7728c1..177f694b4 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, request from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task +from app.db import db bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -57,4 +58,10 @@ def delete_by_id(task_id): return Response(status=204, mimetype="application/json") -# DELETE ALL TASKS \ No newline at end of file +# DELETE ALL TASKS +@bp.delete("") +def delete_all_tasks(): + db.session.query(Task).delete() + db.session.commit() + + return Response(status=204, mimetype="application/json") From d3262f564507b2d3689a34841fac5c06e06afae4 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 1 May 2025 20:06:30 -0700 Subject: [PATCH 11/26] add patch_by_id endpoint --- app/routes/task_routes.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 177f694b4..5512c7503 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -5,12 +5,14 @@ bp = Blueprint("task_bp", __name__, url_prefix="/tasks") + # CREATE ONE TASK @bp.post("") def create_task(): request_body = request.get_json() return create_model_inst_from_dict_with_response(Task, request_body) + # READ ALL TASKS @bp.get("") def get_all_tasks(): @@ -23,6 +25,7 @@ def get_all_tasks(): return response + # READ ONE TASK BY ID @bp.get("/") def get_task_by_id(task_id): @@ -30,6 +33,7 @@ def get_task_by_id(task_id): return task.to_dict() + # UPDATE ONE TASK @bp.update("/") def update_by_id(task_id): @@ -47,6 +51,24 @@ def update_by_id(task_id): # PATCH ONE TASK +@bp.patch("/") +def patch_by_id(task_id): + task = retrieve_model_inst_by_id(Task, task_id) + request_body = request.get_json() + + if "title" in request_body: + task.title = request_body["title"] + if "description" in request_body: + task.description = request_body["description"] + if "completed_at" in request_body: + task.completed_at = request_body["completed_at"] + + db.session.commit() + + return Response(status=204, mimetype="application/json") + + + # DELETE ONE TASK @bp.delete("/ Date: Thu, 1 May 2025 22:43:09 -0700 Subject: [PATCH 12/26] pass tests in wave1, fix bugs --- app/__init__.py | 2 ++ app/models/task.py | 4 ++-- app/routes/routes_helper_utilities.py | 2 +- app/routes/task_routes.py | 19 ++++++++------- tests/test_wave_01.py | 34 +++++++++++++-------------- 5 files changed, 32 insertions(+), 29 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..3a084cdf2 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 app.routes.task_routes import bp as task_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_bp) return app diff --git a/app/models/task.py b/app/models/task.py index a03c92292..15a76b0dc 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -13,9 +13,9 @@ def to_dict(self): "id": self.id, "title": self.title, "description": self.description, - "completed_at": self.completed_at + "is_complete": False if not self.completed_at else self.completed_at } @classmethod def from_dict(cls, dict_data): - return cls(title=dict_data["title"], description=dict_data["description"], completed_at=dict_data["completed_at"]) \ No newline at end of file + return cls(title=dict_data["title"], description=dict_data["description"]) \ No newline at end of file diff --git a/app/routes/routes_helper_utilities.py b/app/routes/routes_helper_utilities.py index b778a3477..68af345f8 100644 --- a/app/routes/routes_helper_utilities.py +++ b/app/routes/routes_helper_utilities.py @@ -21,5 +21,5 @@ def create_model_inst_from_dict_with_response(cls, inst_data): new_instance = cls.from_dict(inst_data) db.session.add(new_instance) db.session.commit() - response = new_instance.to_dict() + response = {"task": new_instance.to_dict()} return response, 201 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 5512c7503..d45fe15ee 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, request +from flask import Blueprint, request, Response, make_response, abort from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task from app.db import db @@ -10,13 +10,18 @@ @bp.post("") def create_task(): request_body = request.get_json() + + if "title" not in request_body or "description" not in request_body: + response_message = {"details": "Invalid data"} + abort(make_response(response_message, 400)) + return create_model_inst_from_dict_with_response(Task, request_body) # READ ALL TASKS @bp.get("") def get_all_tasks(): - query = db.select(Task).order_by(id) + query = db.select(Task).order_by(Task.id) tasks = db.session.scalars(query) response = [] @@ -31,19 +36,17 @@ def get_all_tasks(): def get_task_by_id(task_id): task = retrieve_model_inst_by_id(Task, task_id) - return task.to_dict() + return {"task": task.to_dict()} # UPDATE ONE TASK -@bp.update("/") +@bp.put("/") def update_by_id(task_id): task = retrieve_model_inst_by_id(Task, task_id) request_body = request.get_json() - task.title = request_body["title"] task.description = request_body["description"] - task.completed_at = request_body["completed_at"] db.session.commit() @@ -68,10 +71,8 @@ def patch_by_id(task_id): return Response(status=204, mimetype="application/json") - - # DELETE ONE TASK -@bp.delete("/") def delete_by_id(task_id): task = retrieve_model_inst_by_id(Task, task_id) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 55475db79..33dc7bc90 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,14 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert response_body == {"message": "Task with id <1> is 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 +97,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 +117,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 +128,14 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert response_body == {"message": "Task with id <1> is 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_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -146,7 +146,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,8 +154,8 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert response_body == {"message": "Task with id <1> is not found."} + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -163,7 +163,7 @@ def test_delete_task_not_found(client): assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -180,7 +180,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 ac870a49a84160aa29f036e73db7ebd26e30b463 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Fri, 2 May 2025 19:45:20 -0700 Subject: [PATCH 13/26] refactor hepler functions --- app/routes/routes_helper_utilities.py | 7 ++++++- app/routes/task_routes.py | 5 ----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/routes/routes_helper_utilities.py b/app/routes/routes_helper_utilities.py index 68af345f8..d6d41a2e4 100644 --- a/app/routes/routes_helper_utilities.py +++ b/app/routes/routes_helper_utilities.py @@ -18,7 +18,12 @@ def retrieve_model_inst_by_id(cls, model_id): return model def create_model_inst_from_dict_with_response(cls, inst_data): - new_instance = cls.from_dict(inst_data) + try: + new_instance = cls.from_dict(inst_data) + except KeyError as error: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + db.session.add(new_instance) db.session.commit() response = {"task": new_instance.to_dict()} diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d45fe15ee..204f42acd 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -10,11 +10,6 @@ @bp.post("") def create_task(): request_body = request.get_json() - - if "title" not in request_body or "description" not in request_body: - response_message = {"details": "Invalid data"} - abort(make_response(response_message, 400)) - return create_model_inst_from_dict_with_response(Task, request_body) From bb437d131bf2ead3d3b190eb58f3d8bb7a02a500 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Fri, 2 May 2025 21:10:53 -0700 Subject: [PATCH 14/26] refactor get_all_tasks, add params --- app/routes/task_routes.py | 11 ++++++++++- tests/test_wave_02.py | 4 ++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 204f42acd..d4bc3c224 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,5 @@ from flask import Blueprint, request, Response, make_response, abort +from sqlalchemy import desc from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task from app.db import db @@ -16,7 +17,15 @@ def create_task(): # READ ALL TASKS @bp.get("") def get_all_tasks(): - query = db.select(Task).order_by(Task.id) + query = db.select(Task) + + sort_param = request.args.get("sort") + if sort_param=="desc": + query = query.order_by(desc(Task.title)) + else: + query = query.order_by(Task.title) + + query = query.order_by(Task.id) tasks = db.session.scalars(query) 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 593d5b42f17926f6c3e3122e6f186cc2f591cbbc Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Fri, 2 May 2025 22:09:28 -0700 Subject: [PATCH 15/26] add endpoints for mark complete and mark incomplete --- app/models/task.py | 2 +- app/routes/task_routes.py | 23 +++++++++++++++++++++++ tests/test_wave_03.py | 18 ++++++++++-------- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 15a76b0dc..9cac1f08e 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -13,7 +13,7 @@ def to_dict(self): "id": self.id, "title": self.title, "description": self.description, - "is_complete": False if not self.completed_at else self.completed_at + "is_complete": False if not self.completed_at else True } @classmethod diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d4bc3c224..5b8af79d9 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, request, Response, make_response, abort from sqlalchemy import desc +from datetime import datetime, timezone from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task from app.db import db @@ -75,6 +76,28 @@ def patch_by_id(task_id): return Response(status=204, mimetype="application/json") +# PATCH ONE TASK MARK IT AS COMPLETE +@bp.patch("//mark_complete") +def patch_by_id_mark_complete(task_id): + task = retrieve_model_inst_by_id(Task, task_id) + + task.completed_at = datetime.now(timezone.utc) + db.session.commit() + + return Response(status=204, mimetype="application/json") + + +# PATCH ONE TASK MARK IT AS INCOMPLETE +@bp.patch("//mark_incomplete") +def patch_by_id_mark_incomplete(task_id): + task = retrieve_model_inst_by_id(Task, task_id) + + task.completed_at = None + db.session.commit() + + return Response(status=204, mimetype="application/json") + + # DELETE ONE TASK @bp.delete("/") def delete_by_id(task_id): diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..d02b266eb 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -6,7 +6,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -34,7 +34,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -46,7 +46,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -74,7 +74,7 @@ def test_mark_complete_on_completed_task(client, completed_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -86,7 +86,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -94,14 +94,15 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task with id <1> is not found."} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -109,8 +110,9 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task with id <1> is not found."} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From 73b7846dc8dde7a36418bf0fa9646ab3f1f232f5 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Wed, 7 May 2025 19:42:57 -0700 Subject: [PATCH 16/26] add slak api bot to mark_complete --- app/routes/task_routes.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 5b8af79d9..a6cf54c0d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,9 +1,12 @@ from flask import Blueprint, request, Response, make_response, abort from sqlalchemy import desc from datetime import datetime, timezone +import requests from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id from app.models.task import Task from app.db import db +import os +slack_token = os.environ.get("SLACKBOT_TOKEN") bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -83,6 +86,15 @@ def patch_by_id_mark_complete(task_id): task.completed_at = datetime.now(timezone.utc) db.session.commit() + + # send notification to Slack + headers = {"Authorization": f"Bearer {slack_token}"} + data = { + "channel": "C08NTC26TM1", + "text": f"Someone just completed the task -- {task.title}: {task.description}" + } + + requests.post("https://slack.com/api/chat.postMessage", headers=headers, data=data) return Response(status=204, mimetype="application/json") From a2ed59db8c2f518f126c8e7422c1cc2e9b1cdd09 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Wed, 7 May 2025 21:31:54 -0700 Subject: [PATCH 17/26] add model goal --- app/models/goal.py | 1 + tests/test_wave_05.py | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..a0882ef21 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,4 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 222d10cf0..8246dcc36 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.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_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +12,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 +29,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,7 +46,7 @@ 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 @@ -61,7 +61,7 @@ def test_get_goal_not_found(client): # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,7 +80,7 @@ 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 @@ -94,7 +94,7 @@ def test_update_goal(client, one_goal): # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): raise Exception("Complete test") # Act @@ -107,7 +107,7 @@ def test_update_goal_not_found(client): # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -128,7 +128,7 @@ def test_delete_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_delete_goal_not_found(client): raise Exception("Complete test") @@ -142,7 +142,7 @@ def test_delete_goal_not_found(client): # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) From 446984678a8f17289fde9a6b9f19b18579196750 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Wed, 7 May 2025 21:39:57 -0700 Subject: [PATCH 18/26] add methods to goal model --- app/models/goal.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/models/goal.py b/app/models/goal.py index a0882ef21..6c82c1e76 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,4 +3,13 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) - title: Mapped[str] \ No newline at end of file + title: Mapped[str] + + def to_dict(self): + return dict( + id=self.id, + title=self.title + ) + + def from_dict(cls, goal_data): + return cls(title=goal_data["title"]) \ No newline at end of file From eaf8e4f4dedc397031c21f9136dd1fd0c9e5288f Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Wed, 7 May 2025 22:11:25 -0700 Subject: [PATCH 19/26] add post rout to goal, fix somw typos --- app/__init__.py | 4 ++++ app/models/goal.py | 1 + app/routes/goal_routes.py | 17 +++++++++++++- app/routes/routes_helper_utilities.py | 2 +- app/routes/task_routes.py | 1 + migrations/versions/6c80ec5add5b_.py | 32 +++++++++++++++++++++++++++ 6 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/6c80ec5add5b_.py diff --git a/app/__init__.py b/app/__init__.py index 3a084cdf2..1c8d5d0a8 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,6 +2,8 @@ from .db import db, migrate from .models import task, goal from app.routes.task_routes import bp as task_bp +from app.routes.goal_routes import bp as goal_bp + import os def create_app(config=None): @@ -20,5 +22,7 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(task_bp) + app.register_blueprint(goal_bp) + return app diff --git a/app/models/goal.py b/app/models/goal.py index 6c82c1e76..3f4201fd2 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -11,5 +11,6 @@ def to_dict(self): 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/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..9ebdbf8c7 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,16 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response, make_response, abort +from sqlalchemy import desc +from datetime import datetime, timezone +import requests +from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id +from app.models.task import Task +from app.models.goal import Goal +from app.db import db + +bp = Blueprint("goal_bp", __name__, url_prefix="/goals") + + +@bp.post("") +def create_goal(): + request_body = request.get_json() + return create_model_inst_from_dict_with_response(Goal, request_body) diff --git a/app/routes/routes_helper_utilities.py b/app/routes/routes_helper_utilities.py index d6d41a2e4..ba6d53bf8 100644 --- a/app/routes/routes_helper_utilities.py +++ b/app/routes/routes_helper_utilities.py @@ -26,5 +26,5 @@ def create_model_inst_from_dict_with_response(cls, inst_data): db.session.add(new_instance) db.session.commit() - response = {"task": new_instance.to_dict()} + response = {f"{cls.__name__.lower()}": new_instance.to_dict()} return response, 201 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index a6cf54c0d..20b9f8c9a 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -6,6 +6,7 @@ from app.models.task import Task from app.db import db import os + slack_token = os.environ.get("SLACKBOT_TOKEN") bp = Blueprint("task_bp", __name__, url_prefix="/tasks") diff --git a/migrations/versions/6c80ec5add5b_.py b/migrations/versions/6c80ec5add5b_.py new file mode 100644 index 000000000..94bed6fbd --- /dev/null +++ b/migrations/versions/6c80ec5add5b_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: 6c80ec5add5b +Revises: c62b77d928bc +Create Date: 2025-05-07 21:32:10.034895 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6c80ec5add5b' +down_revision = 'c62b77d928bc' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.add_column(sa.Column('title', sa.String(), nullable=False)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### From 7229f141ea22b08bfd7b561b8ee0d841940e25e0 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Wed, 7 May 2025 22:51:48 -0700 Subject: [PATCH 20/26] add get_one_goal --- app/routes/goal_routes.py | 15 ++++++++++++++- app/routes/routes_helper_utilities.py | 4 ++++ tests/test_wave_05.py | 6 ++++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 9ebdbf8c7..304c52f73 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,7 +2,7 @@ from sqlalchemy import desc from datetime import datetime, timezone import requests -from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id +from app.routes.routes_helper_utilities import create_model_inst_from_dict_with_response, retrieve_model_inst_by_id, nested_dict from app.models.task import Task from app.models.goal import Goal from app.db import db @@ -14,3 +14,16 @@ def create_goal(): request_body = request.get_json() return create_model_inst_from_dict_with_response(Goal, request_body) + +@bp.get("") +def get_saved_goals(): + goals = db.session.scalars(db.select(Goal).order_by(Goal.id)) + return [goal.to_dict() for goal in goals] + +@bp.get("/") +def get_one_goal(goal_id): + goal = retrieve_model_inst_by_id(Goal, goal_id) + return nested_dict(Goal, goal) + + + diff --git a/app/routes/routes_helper_utilities.py b/app/routes/routes_helper_utilities.py index ba6d53bf8..9b0c55f1a 100644 --- a/app/routes/routes_helper_utilities.py +++ b/app/routes/routes_helper_utilities.py @@ -28,3 +28,7 @@ def create_model_inst_from_dict_with_response(cls, inst_data): db.session.commit() response = {f"{cls.__name__.lower()}": new_instance.to_dict()} return response, 201 + +def nested_dict(cls, instance): + return {f"{cls.__name__.lower()}": instance.to_dict()} + \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 8246dcc36..5fda37d14 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -48,16 +48,18 @@ def test_get_goal(client, one_goal): # @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): - pass + # pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + # raise Exception("Complete test") # Assert # ---- Complete Test ---- # assertion 1 goes here + assert response_body["message"] == "Goal with id <1> is not found." # assertion 2 goes here + assert response.status_code == 404 # ---- Complete Test ---- From 05c2d3cf4aaa82c2a9e073e3e5589c19d5dfe176 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 8 May 2025 12:41:50 -0700 Subject: [PATCH 21/26] add update and delete routes for goal, passed all tests --- app/routes/goal_routes.py | 16 ++++++++++++++++ tests/test_wave_05.py | 34 +++++++++++++++++++++++++--------- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 304c52f73..67eb5c77f 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -25,5 +25,21 @@ def get_one_goal(goal_id): goal = retrieve_model_inst_by_id(Goal, goal_id) return nested_dict(Goal, goal) +@bp.put("/") +def update_one_goal(goal_id): + goal = retrieve_model_inst_by_id(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_one_goal(goal_id): + goal = retrieve_model_inst_by_id(Goal, goal_id) + db.session.delete(goal) + db.session.commit() + + return Response(status=204, mimetype="application/json") diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 5fda37d14..a02bd3c9d 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,3 +1,5 @@ +from app.models.goal import Goal +from app.db import db import pytest @@ -84,28 +86,37 @@ def test_create_goal(client): # @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 ---- - - # Assert + response = client.put("/goals/1", json={"title": "Updated Goal Title"}) # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 204 + + query = db.select(Goal).where(Goal.id == 1) + goal = db.session.scalar(query) + # assertion 2 goes here + assert goal.title == "Updated Goal Title" # assertion 3 goes here + assert goal.id == 1 # ---- Complete Assertions Here ---- # @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 + response = client.put("/goals/1", json={"title": "Updated Goal Title"}) # Assert + response_body = response.get_json() # ---- Complete Act Here ---- - # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"message": "Goal with id <1> is not found."} # ---- Complete Assertions Here ---- @@ -123,24 +134,29 @@ 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") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** + assert response_body == {"message": "Goal with id <1> is not found."} # ***************************************************************** # @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") # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 404 + + response_body = response.get_json() # assertion 2 goes here + assert response_body == {"message": "Goal with id <1> is not found."} + # ---- Complete Assertions Here ---- From 272f4f21827e283a10db3f41fffa1aa4b8527967 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 8 May 2025 13:00:26 -0700 Subject: [PATCH 22/26] add raletionship between task and goal --- app/models/goal.py | 8 ++++- app/models/task.py | 11 +++++- ...03d6f6_add_goal_id_column_to_task_model.py | 34 +++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/5e99fa03d6f6_add_goal_id_column_to_task_model.py diff --git a/app/models/goal.py b/app/models/goal.py index 3f4201fd2..36185f95c 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,9 +1,15 @@ -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") def to_dict(self): return dict( diff --git a/app/models/task.py b/app/models/task.py index 9cac1f08e..007045226 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,12 +1,21 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey from datetime import datetime +from typing import Optional from ..db import db +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .goal import Goal + + class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] description: Mapped[str] completed_at: Mapped[datetime] = mapped_column(nullable=True) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped["Goal"] = relationship(back_populates="tasks") def to_dict(self): return { diff --git a/migrations/versions/5e99fa03d6f6_add_goal_id_column_to_task_model.py b/migrations/versions/5e99fa03d6f6_add_goal_id_column_to_task_model.py new file mode 100644 index 000000000..6f3130b09 --- /dev/null +++ b/migrations/versions/5e99fa03d6f6_add_goal_id_column_to_task_model.py @@ -0,0 +1,34 @@ +"""add goal_id column to Task model + +Revision ID: 5e99fa03d6f6 +Revises: 6c80ec5add5b +Create Date: 2025-05-08 12:58:20.334951 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5e99fa03d6f6' +down_revision = '6c80ec5add5b' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### From 3b42148296fd3abce48f4ba60a13e50e0d34ad72 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 8 May 2025 21:48:30 -0700 Subject: [PATCH 23/26] fixed goal method, passed all tests --- app/models/goal.py | 22 +++++++++++++++++----- app/models/task.py | 18 +++++++++++------- app/routes/goal_routes.py | 33 ++++++++++++++++++++++++++++++++- tests/test_wave_06.py | 17 +++++++++-------- 4 files changed, 69 insertions(+), 21 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 36185f95c..290ba626b 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -10,13 +10,25 @@ 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, include_empty_tasks=False): + goal_as_dict = {} + goal_as_dict["id"] = self.id + goal_as_dict["title"] = self.title + + if self.tasks: + goal_as_dict["tasks"] = [task.to_dict() for task in self.tasks] + if not self.tasks and include_empty_tasks == True: + goal_as_dict["tasks"] = [] - def to_dict(self): - return dict( - id=self.id, - title=self.title - ) + return goal_as_dict + # def to_dict_mandatory_tasks_list(self): + # goal_as_dict = self.to_dict() + # goal_as_dict["tasks"] = [task.to_dict() for task in self.tasks] + # return goal_as_dict + + @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 007045226..4b7118ba6 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -16,14 +16,18 @@ class Task(db.Model): completed_at: Mapped[datetime] = mapped_column(nullable=True) goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) goal: Mapped["Goal"] = relationship(back_populates="tasks") - + def to_dict(self): - return { - "id": self.id, - "title": self.title, - "description": self.description, - "is_complete": False if not self.completed_at else True - } + 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"] = False if not self.completed_at else True + + if self.goal: + task_as_dict["goal_id"] = self.goal.id + + return task_as_dict @classmethod def from_dict(cls, dict_data): diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 67eb5c77f..cab7f38ce 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -9,22 +9,52 @@ bp = Blueprint("goal_bp", __name__, url_prefix="/goals") - +# POST ONE GOAL, RETURN {"GOAL": {GOAL DICTIONARY}} @bp.post("") def create_goal(): request_body = request.get_json() return create_model_inst_from_dict_with_response(Goal, request_body) +# ADD EXISTING TASK IDS TO EXISTING GOAL, RETURN {"ID":..., "TASK_IDS": [...]} +@bp.post("//tasks") +def add_task_ids_to_goal(goal_id): + goal = retrieve_model_inst_by_id(Goal, goal_id) + request_body = request.get_json() + + # remove existing task from that goal + query = db.select(Task).where(Task.goal_id==1) + old_tasks = db.session.scalars(query) + for task in old_tasks: + task.goal_id = None + + # add tasks to the goal + for task_id in request_body["task_ids"]: + task = retrieve_model_inst_by_id(Task, task_id) + task.goal_id = goal_id + + db.session.commit() + return {"id": int(goal_id), + "task_ids": [task.id for task in goal.tasks]} + +# GET TASKS FOR ONE GOAL, RETURN GOAL DICTIONARY WITH TASKS LIST +@bp.get("//tasks") +def get_tasks_of_one_goal(goal_id): + goal = retrieve_model_inst_by_id(Goal, goal_id) + return goal.to_dict(include_empty_tasks=True) + +# GET ALL GOALS @bp.get("") def get_saved_goals(): goals = db.session.scalars(db.select(Goal).order_by(Goal.id)) return [goal.to_dict() for goal in goals] +# GET GOAL BY ID @bp.get("/") def get_one_goal(goal_id): goal = retrieve_model_inst_by_id(Goal, goal_id) return nested_dict(Goal, goal) +# UPDATE GOAL TITLE @bp.put("/") def update_one_goal(goal_id): goal = retrieve_model_inst_by_id(Goal, goal_id) @@ -34,6 +64,7 @@ def update_one_goal(goal_id): db.session.commit() return Response(status=204, mimetype="application/json") +# DELETE ONE GOAL @bp.delete("/") def delete_one_goal(goal_id): goal = retrieve_model_inst_by_id(Goal, goal_id) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 0317f835a..f38661c0b 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -3,8 +3,8 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") -def test_post_task_ids_to_goal(client, one_goal, three_tasks): +# @pytest.mark.skip(reason="No way to test this feature yet") +def test_post_task_ids_to_goal(client, one_goal, three_tasks): # why we replace task 1 # Act response = client.post("/goals/1/tasks", json={ "task_ids": [1, 2, 3] @@ -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") @@ -54,13 +54,14 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** + assert response_body["message"] == "Goal with id <1> is 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_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -77,7 +78,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 +103,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 34c7be90ed2ada96b3297147eba9c9e13784dd24 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 8 May 2025 22:06:32 -0700 Subject: [PATCH 24/26] fix some typos --- app/routes/goal_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index cab7f38ce..8bf9afcf4 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -21,13 +21,13 @@ def add_task_ids_to_goal(goal_id): goal = retrieve_model_inst_by_id(Goal, goal_id) request_body = request.get_json() - # remove existing task from that goal + # remove connection of existing task from that goal query = db.select(Task).where(Task.goal_id==1) old_tasks = db.session.scalars(query) for task in old_tasks: task.goal_id = None - # add tasks to the goal + # add connections of new tasks to the goal for task_id in request_body["task_ids"]: task = retrieve_model_inst_by_id(Task, task_id) task.goal_id = goal_id From f7cd9ea316fd378d58ea3b6ebfe036d0cb015d9c Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Thu, 8 May 2025 22:50:26 -0700 Subject: [PATCH 25/26] add dotenv to init --- app/__init__.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 1c8d5d0a8..ecb0219f2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,3 +1,6 @@ +from dotenv import load_dotenv +load_dotenv() + from flask import Flask from .db import db, migrate from .models import task, goal From 87e9274952fae91d3da0aa83a20118a1386178a9 Mon Sep 17 00:00:00 2001 From: sashavershkova Date: Fri, 9 May 2025 00:01:51 -0700 Subject: [PATCH 26/26] final version --- app/__init__.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index ecb0219f2..35fff9f6c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,5 +1,3 @@ -from dotenv import load_dotenv -load_dotenv() from flask import Flask from .db import db, migrate