From 51cb40d5b8558030d22e1002f2574f31cdc7c6b4 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 14:27:18 -0700 Subject: [PATCH 01/32] Initialize database and create migration files --- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 4 files changed, 166 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# 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 + +[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 + +[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..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +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') + +# 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', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# 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 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=target_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.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_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 58da86a24d017eef197665ac5681a261469437e8 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 15:08:31 -0700 Subject: [PATCH 02/32] Create Task model with id, title, description, completed_by columns --- app/models/task.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/models/task.py b/app/models/task.py index c91ab281f..4bb72b91b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -3,3 +3,6 @@ class Task(db.Model): task_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.Text) + completed_at = db.Column(db.DateTime, nullable=True, default=None) \ No newline at end of file From 7cefaafd9b573c7656a43c49d93b899f2ffc166b Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 15:09:33 -0700 Subject: [PATCH 03/32] Run migrate and upgrade after model changes --- migrations/versions/ae7ff381b019_.py | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 migrations/versions/ae7ff381b019_.py diff --git a/migrations/versions/ae7ff381b019_.py b/migrations/versions/ae7ff381b019_.py new file mode 100644 index 000000000..d50d1e0c2 --- /dev/null +++ b/migrations/versions/ae7ff381b019_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: ae7ff381b019 +Revises: +Create Date: 2023-05-03 15:08:49.204262 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'ae7ff381b019' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('task_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 5c0a5cef2aa485981ce9ce3b8539c5b8c4463193 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 16:00:26 -0700 Subject: [PATCH 04/32] Register Task blueprint --- app/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..845c61776 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,7 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from .routes import task_bp + app.register_blueprint(task_bp) return app From 18debd5042f0505b8040992b3f0f4ad088eea699 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 16:01:43 -0700 Subject: [PATCH 05/32] Add GET route and function get_all_tasks --- app/routes.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 3aae38d49..a8d264b0f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1 +1,10 @@ -from flask import Blueprint \ No newline at end of file +from flask import abort, Blueprint, jsonify, make_response, request +from app import db +from app.models.task import Task + + +task_bp = Blueprint("task", __name__, url_prefix="/tasks") + +@task_bp.route("", methods=["GET"]) +def get_all_tasks(): + return jsonify([]), 200 \ No newline at end of file From 5d008bc70f1c828a9586ed610a71a669ecc1ef8f Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 16:24:36 -0700 Subject: [PATCH 06/32] Refactor get_all_tasks to return a list of tasks with the correct key-value pairs --- app/routes.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index a8d264b0f..d812b4059 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,4 +7,19 @@ @task_bp.route("", methods=["GET"]) def get_all_tasks(): - return jsonify([]), 200 \ No newline at end of file + response = [] + tasks = Task.query.all() + + for task in tasks: + task_dict = { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": False + } + if task.completed_at is not None: + task_dict["is_complete"] = True + + response.append(task_dict) + + return jsonify(response), 200 \ No newline at end of file From 6f5b118d10fa7bf1ae3434b33226a0847c785901 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 16:35:44 -0700 Subject: [PATCH 07/32] Add GET route and function get_one_task --- app/routes.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index d812b4059..f218aec87 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,6 +5,7 @@ task_bp = Blueprint("task", __name__, url_prefix="/tasks") + @task_bp.route("", methods=["GET"]) def get_all_tasks(): response = [] @@ -22,4 +23,19 @@ def get_all_tasks(): response.append(task_dict) - return jsonify(response), 200 \ No newline at end of file + return jsonify(response), 200 + + +@task_bp.route("/", methods=["GET"]) +def get_one_task(task_id): + task = Task.query.get_or_404(task_id) + task_dict = { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": False + } + if task.completed_at is not None: + task_dict["is_complete"] = True + + return {"task": task_dict}, 200 \ No newline at end of file From 24b88d38d3198c02ed29a0ce30ea5e6a1bb73c51 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 16:49:44 -0700 Subject: [PATCH 08/32] Add to_dict class method to Task and refactor routes with it --- app/models/task.py | 14 +++++++++++++- app/routes.py | 35 +++++++++++++++-------------------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 4bb72b91b..049668d29 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -5,4 +5,16 @@ class Task(db.Model): task_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) description = db.Column(db.Text) - completed_at = db.Column(db.DateTime, nullable=True, default=None) \ No newline at end of file + completed_at = db.Column(db.DateTime, nullable=True, default=None) + + def to_dict(self): + task = { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": False + } + if self.completed_at is not None: + task["is_complete"] = True + + return task \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index f218aec87..ca4e7c0cb 100644 --- a/app/routes.py +++ b/app/routes.py @@ -12,16 +12,7 @@ def get_all_tasks(): tasks = Task.query.all() for task in tasks: - task_dict = { - "id": task.task_id, - "title": task.title, - "description": task.description, - "is_complete": False - } - if task.completed_at is not None: - task_dict["is_complete"] = True - - response.append(task_dict) + response.append(task.to_dict()) return jsonify(response), 200 @@ -29,13 +20,17 @@ def get_all_tasks(): @task_bp.route("/", methods=["GET"]) def get_one_task(task_id): task = Task.query.get_or_404(task_id) - task_dict = { - "id": task.task_id, - "title": task.title, - "description": task.description, - "is_complete": False - } - if task.completed_at is not None: - task_dict["is_complete"] = True - - return {"task": task_dict}, 200 \ No newline at end of file + return {"task": task.to_dict()}, 200 + + +# @task_bp.route("", methods=["POST"]) +# def create_new_task(): +# request_body = request.get_json() +# new_task = Task( +# "title": request.title, +# "description": request.description +# ) + + + +# return {"task": None}, 201 \ No newline at end of file From 1864a82339d47da414bf5c10abf48ce9e1042781 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:09:17 -0700 Subject: [PATCH 09/32] Update task_id attribute to autoincrement --- app/models/task.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/task.py b/app/models/task.py index 049668d29..815b2f7da 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -2,7 +2,7 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + task_id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String) description = db.Column(db.Text) completed_at = db.Column(db.DateTime, nullable=True, default=None) From 78869feafa8bcc730e894803c3056dd3d0e029c9 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:09:34 -0700 Subject: [PATCH 10/32] Add POST method to create new task --- app/routes.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index ca4e7c0cb..3bd6345c9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -23,14 +23,14 @@ def get_one_task(task_id): return {"task": task.to_dict()}, 200 -# @task_bp.route("", methods=["POST"]) -# def create_new_task(): -# request_body = request.get_json() -# new_task = Task( -# "title": request.title, -# "description": request.description -# ) - - - -# return {"task": None}, 201 \ No newline at end of file +@task_bp.route("", methods=["POST"]) +def create_new_task(): + request_body = request.get_json() + new_task = Task( + title=request_body["title"], + description=request_body["description"] + ) + db.session.add(new_task) + db.session.commit() + + return {"task": new_task.to_dict()}, 201 \ No newline at end of file From 50afbaacb2fd2cd2f1677ccea58bada2a59cc40f Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:12:30 -0700 Subject: [PATCH 11/32] Add PUT method to update one task --- app/routes.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 3bd6345c9..a5634b723 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,4 +33,17 @@ def create_new_task(): db.session.add(new_task) db.session.commit() - return {"task": new_task.to_dict()}, 201 \ No newline at end of file + return {"task": new_task.to_dict()}, 201 + + +@task_bp.route("/", methods=["PUT"]) +def update_one_task(task_id): + task = Task.query.get_or_404(task_id) + request_body = request.get_json() + + task.title = request_body["title"] + task.description = request_body["description"] + + db.session.commit() + + return {"task": task.to_dict()}, 200 \ No newline at end of file From 68aaafc9d7403ca049ea285da42c69ed81f54692 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:20:08 -0700 Subject: [PATCH 12/32] Add DELETE method to delete one task --- app/routes.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index a5634b723..643748bac 100644 --- a/app/routes.py +++ b/app/routes.py @@ -46,4 +46,15 @@ def update_one_task(task_id): db.session.commit() - return {"task": task.to_dict()}, 200 \ No newline at end of file + return {"task": task.to_dict()}, 200 + + +@task_bp.route("/", methods=["DELETE"]) +def delete_one_task(task_id): + task = Task.query.get_or_404(task_id) + + db.session.delete(task) + db.session.commit() + + return {"details": (f'Task {task.task_id} "{task.title}" ' + 'successfully deleted')}, 200 \ No newline at end of file From 4d1405742f18f197dee0a2ba7ba29ed2863b4a04 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:23:42 -0700 Subject: [PATCH 13/32] Refactor create_new_task POST method to validate title and description --- app/routes.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 643748bac..f9c09a3c6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -26,10 +26,14 @@ def get_one_task(task_id): @task_bp.route("", methods=["POST"]) def create_new_task(): request_body = request.get_json() - new_task = Task( - title=request_body["title"], - description=request_body["description"] - ) + try: + new_task = Task( + title=request_body["title"], + description=request_body["description"] + ) + except KeyError: + return {"details": "Invalid data"}, 400 + db.session.add(new_task) db.session.commit() From 6431a71dadb5f441f2b3c63924493a72ac961268 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 3 May 2023 17:24:22 -0700 Subject: [PATCH 14/32] Remove skip decorators and finish test assertions --- tests/test_wave_01.py | 31 ++++--------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..71f9afa16 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,6 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -13,7 +12,6 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@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") @@ -32,7 +30,6 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -51,7 +48,6 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -59,14 +55,9 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body is None - 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") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -93,7 +84,6 @@ def test_create_task(client): assert new_task.completed_at == None -@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={ @@ -119,7 +109,7 @@ def test_update_task(client, one_task): assert task.completed_at == None -@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={ @@ -130,14 +120,9 @@ 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 is None -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -152,7 +137,6 @@ def test_delete_task(client, one_task): assert Task.query.get(1) == None -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -160,16 +144,10 @@ 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 is None assert Task.query.all() == [] -@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={ @@ -186,7 +164,6 @@ def test_create_task_must_contain_title(client): assert Task.query.all() == [] -@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 25e60bbb167e94eab43ca0c960379a32ffd7b441 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 17:53:57 -0700 Subject: [PATCH 15/32] Add query params for GET route --- app/routes.py | 12 ++++++++++-- tests/test_wave_02.py | 2 -- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index f9c09a3c6..ac3ee3b1a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ from flask import abort, Blueprint, jsonify, make_response, request +from sqlalchemy import desc, asc from app import db from app.models.task import Task @@ -8,9 +9,16 @@ @task_bp.route("", methods=["GET"]) def get_all_tasks(): - response = [] - tasks = Task.query.all() + sort_query = request.args.get("sort") + if sort_query == "asc": + tasks = Task.query.order_by(asc(Task.title)) + elif sort_query == "desc": + tasks = Task.query.order_by(desc(Task.title)) + else: + tasks = Task.query.all() + + response = [] for task in tasks: response.append(task.to_dict()) diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..e03e5c99a 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,6 @@ import pytest -@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 +28,6 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@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 831be221229f86d943fe57535004513edadca6c0 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 18:38:56 -0700 Subject: [PATCH 16/32] Add mark_complete and mark_incomplete routes. --- app/routes.py | 23 +++++++++++++++++++++++ tests/test_wave_03.py | 19 +++---------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/app/routes.py b/app/routes.py index ac3ee3b1a..9c637f158 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,6 +2,7 @@ from sqlalchemy import desc, asc from app import db from app.models.task import Task +from datetime import datetime, timezone task_bp = Blueprint("task", __name__, url_prefix="/tasks") @@ -61,6 +62,28 @@ def update_one_task(task_id): return {"task": task.to_dict()}, 200 +@task_bp.route("//mark_complete", methods=["PATCH"]) +def mark_complete_one_task(task_id): + task = Task.query.get_or_404(task_id) + + task.completed_at = datetime.now(timezone.utc) + + db.session.commit() + + return {"task": task.to_dict()}, 200 + + +@task_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_incomplete_one_task(task_id): + task = Task.query.get_or_404(task_id) + + task.completed_at = None + + db.session.commit() + + return {"task": task.to_dict()}, 200 + + @task_bp.route("/", methods=["DELETE"]) def delete_one_task(task_id): task = Task.query.get_or_404(task_id) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..f1fce5234 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,6 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -42,7 +41,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at -@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") @@ -62,7 +61,6 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +97,6 @@ def test_mark_complete_on_completed_task(client, completed_task): assert Task.query.get(1).completed_at -@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") @@ -119,7 +116,6 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at == None -@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") @@ -127,14 +123,9 @@ def test_mark_complete_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 not response_body -@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") @@ -142,8 +133,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 not response_body From 155b47dc5b5ecc4029348c55cb017abbd934fa56 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:09:46 -0700 Subject: [PATCH 17/32] Add Slack Bot --- app/routes.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 9c637f158..55523b027 100644 --- a/app/routes.py +++ b/app/routes.py @@ -3,11 +3,22 @@ from app import db from app.models.task import Task from datetime import datetime, timezone +import requests +import os - +SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN") task_bp = Blueprint("task", __name__, url_prefix="/tasks") +def call_slack_API(title): + r = requests.post('https://slack.com/api/chat.postMessage', + data={ + 'channel': 'C05N61M2JHG', + 'text': f'Task {title} was marked complete!'}, + headers={'Authorization': SLACK_API_TOKEN}) + return None + + @task_bp.route("", methods=["GET"]) def get_all_tasks(): @@ -67,7 +78,8 @@ def mark_complete_one_task(task_id): task = Task.query.get_or_404(task_id) task.completed_at = datetime.now(timezone.utc) - + call_slack_API(task.title) + db.session.commit() return {"task": task.to_dict()}, 200 From 18d5384c3e910b6d876af8e1c449125cf222a111 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:16:15 -0700 Subject: [PATCH 18/32] Modify Goal object with title field. Register blueprint. --- app/__init__.py | 3 ++- app/models/goal.py | 8 ++++++++ app/models/task.py | 3 +-- app/routes.py | 23 ++++++++++++++++++++++- migrations/versions/bbd0dc823856_.py | 28 ++++++++++++++++++++++++++++ 5 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 migrations/versions/bbd0dc823856_.py diff --git a/app/__init__.py b/app/__init__.py index 845c61776..11c0a9d92 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,7 +30,8 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from .routes import task_bp + from .routes import task_bp, goal_bp 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 b0ed11dd8..68bf05c76 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,11 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + + def to_dict(self): + goal = { + "id": self.goal_id, + "title": self.title, + } + return goal diff --git a/app/models/task.py b/app/models/task.py index 815b2f7da..340e36ffc 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -13,8 +13,7 @@ def to_dict(self): "title": self.title, "description": self.description, "is_complete": False - } + } if self.completed_at is not None: task["is_complete"] = True - return task \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 55523b027..45b14237d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,6 +8,8 @@ SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN") task_bp = Blueprint("task", __name__, url_prefix="/tasks") +goal_bp = Blueprint("goal", __name__, url_prefix="/goals") + def call_slack_API(title): @@ -19,6 +21,8 @@ def call_slack_API(title): return None +''' TASK ROUTES ''' + @task_bp.route("", methods=["GET"]) def get_all_tasks(): @@ -104,4 +108,21 @@ def delete_one_task(task_id): db.session.commit() return {"details": (f'Task {task.task_id} "{task.title}" ' - 'successfully deleted')}, 200 \ No newline at end of file + 'successfully deleted')}, 200 + + +''' GOAL ROUTES ''' +@goal_bp.route("", methods=["POST"]) +def create_new_goal(): + request_body = request.get_json() + try: + new_goal = Goal( + title=request_body["title"], + ) + except KeyError: + return {"details": "Invalid data"}, 400 + + db.session.add(new_goal) + db.session.commit() + + return {"goal": new_goal.to_dict()}, 201 \ No newline at end of file diff --git a/migrations/versions/bbd0dc823856_.py b/migrations/versions/bbd0dc823856_.py new file mode 100644 index 000000000..ac5e527c4 --- /dev/null +++ b/migrations/versions/bbd0dc823856_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: bbd0dc823856 +Revises: ae7ff381b019 +Create Date: 2023-08-16 20:11:20.706111 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bbd0dc823856' +down_revision = 'ae7ff381b019' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('title', sa.String(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('goal', 'title') + # ### end Alembic commands ### From d104f96b3dccef5e66633288944ee8e08a0ab72d Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:17:27 -0700 Subject: [PATCH 19/32] Create POST route for Goal --- app/routes.py | 1 + 1 file changed, 1 insertion(+) diff --git a/app/routes.py b/app/routes.py index 45b14237d..ea6ec0712 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,6 +2,7 @@ from sqlalchemy import desc, asc from app import db from app.models.task import Task +from app.models.goal import Goal from datetime import datetime, timezone import requests import os From 5d0eec90a1f42cb57831d3f1eb576cc59c3434ad Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:22:36 -0700 Subject: [PATCH 20/32] Add GET ALL route for Goal --- app/routes.py | 20 ++++++++++++++++++-- tests/test_wave_05.py | 3 --- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index ea6ec0712..026ea696d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -26,7 +26,6 @@ def call_slack_API(title): @task_bp.route("", methods=["GET"]) def get_all_tasks(): - sort_query = request.args.get("sort") if sort_query == "asc": tasks = Task.query.order_by(asc(Task.title)) @@ -126,4 +125,21 @@ def create_new_goal(): db.session.add(new_goal) db.session.commit() - return {"goal": new_goal.to_dict()}, 201 \ No newline at end of file + return {"goal": new_goal.to_dict()}, 201 + + +@goal_bp.route("", methods=["GET"]) +def get_all_goals(): + sort_query = request.args.get("sort") + if sort_query == "asc": + goals = Goal.query.order_by(asc(Goal.title)) + elif sort_query == "desc": + goals = Goal.query.order_by(desc(Goal.title)) + else: + goals = Goal.query.all() + + response = [] + for goal in goals: + response.append(goal.to_dict()) + + return jsonify(response), 200 \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..11474dfbb 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,6 @@ import pytest -@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 +11,6 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@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") @@ -61,7 +59,6 @@ def test_get_goal_not_found(client): # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ From 4a17547a0e7e5d51c5c0babd756c7edb4fd643da Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:26:20 -0700 Subject: [PATCH 21/32] Add GET one route for Goal --- app/routes.py | 8 +++++++- tests/test_wave_05.py | 10 ++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 026ea696d..b9b33c480 100644 --- a/app/routes.py +++ b/app/routes.py @@ -142,4 +142,10 @@ def get_all_goals(): for goal in goals: response.append(goal.to_dict()) - return jsonify(response), 200 \ No newline at end of file + return jsonify(response), 200 + + +@goal_bp.route("/", methods=["GET"]) +def get_one_task(goal_id): + goal = Goal.query.get_or_404(goal_id) + return {"goal": goal.to_dict()}, 200 \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 11474dfbb..674fd3765 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -27,7 +27,6 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -44,19 +43,14 @@ 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 # 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 not response_body def test_create_goal(client): From 1f04c318dfadc41447e7b9a18f9704348202faad Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:37:02 -0700 Subject: [PATCH 22/32] Add PUT routes for Goal --- app/routes.py | 12 ++++++++++++ tests/test_wave_05.py | 38 +++++++++++++++++++++----------------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/app/routes.py b/app/routes.py index b9b33c480..795e8156d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -148,4 +148,16 @@ def get_all_goals(): @goal_bp.route("/", methods=["GET"]) def get_one_task(goal_id): goal = Goal.query.get_or_404(goal_id) + return {"goal": goal.to_dict()}, 200 + + +@goal_bp.route("/", methods=["PUT"]) +def update_one_task(goal_id): + goal = Goal.query.get_or_404(goal_id) + request_body = request.get_json() + + goal.title = request_body["title"] + + db.session.commit() + return {"goal": goal.to_dict()}, 200 \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 674fd3765..85515ed3e 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,3 +1,4 @@ +from app.models.goal import Goal import pytest @@ -44,7 +45,6 @@ def test_get_goal(client, one_goal): def test_get_goal_not_found(client): - pass # Act response = client.get("/goals/1") response_body = response.get_json() @@ -71,31 +71,35 @@ 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") - # 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 - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title", + } + } + goal = Goal.query.get(1) + assert goal.title == "Updated Goal Title" -@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 is None @pytest.mark.skip(reason="No way to test this feature yet") From a77f7274b1d345cf4f43bee9334af2adffa88945 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:41:01 -0700 Subject: [PATCH 23/32] Add DELETE route for Goal --- app/routes.py | 17 ++++++++++++++--- tests/test_wave_05.py | 21 +++++++-------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/app/routes.py b/app/routes.py index 795e8156d..383813366 100644 --- a/app/routes.py +++ b/app/routes.py @@ -146,13 +146,13 @@ def get_all_goals(): @goal_bp.route("/", methods=["GET"]) -def get_one_task(goal_id): +def get_one_goal(goal_id): goal = Goal.query.get_or_404(goal_id) return {"goal": goal.to_dict()}, 200 @goal_bp.route("/", methods=["PUT"]) -def update_one_task(goal_id): +def update_one_goal(goal_id): goal = Goal.query.get_or_404(goal_id) request_body = request.get_json() @@ -160,4 +160,15 @@ def update_one_task(goal_id): db.session.commit() - return {"goal": goal.to_dict()}, 200 \ No newline at end of file + return {"goal": goal.to_dict()}, 200 + + +@goal_bp.route("/", methods=["DELETE"]) +def delete_one_goal(goal_id): + goal = Goal.query.get_or_404(goal_id) + + db.session.delete(goal) + db.session.commit() + + return {"details": (f'Goal {goal.goal_id} "{goal.title}" ' + 'successfully deleted')}, 200 \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 85515ed3e..d2df8d2bb 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -102,7 +102,6 @@ def test_update_goal_not_found(client): assert response_body is None -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -117,26 +116,20 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") + response_body = response.get_json() assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert not response_body -@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 is None + assert Goal.query.all() == [] @pytest.mark.skip(reason="No way to test this feature yet") From 2bfd36c413818b4ca9eefb01d4554b1a24ea4e0f Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:41:31 -0700 Subject: [PATCH 24/32] Confirm 400 error for invalid POST request --- tests/test_wave_05.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index d2df8d2bb..e2576224c 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -132,7 +132,6 @@ def test_delete_goal_not_found(client): assert Goal.query.all() == [] -@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 ec6fc1b404d594ff07a7288fa70caf7ab52353ad Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 20:48:42 -0700 Subject: [PATCH 25/32] Update Task and Goal models. Add from_dict method to Task. --- app/__init__.py | 3 ++- app/models/goal.py | 2 ++ app/models/task.py | 10 +++++++++- app/routes.py | 1 + migrations/versions/374d64514e06_.py | 30 ++++++++++++++++++++++++++++ 5 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/374d64514e06_.py diff --git a/app/__init__.py b/app/__init__.py index 11c0a9d92..0c3d11930 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,8 +30,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from .routes import task_bp, goal_bp + from .routes import task_bp, goal_bp, goal_task_bp app.register_blueprint(task_bp) app.register_blueprint(goal_bp) + app.register_blueprint(goal_task_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 68bf05c76..674188419 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,10 +4,12 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) + tasks = db.relationship("Task", back_populates="goal") def to_dict(self): goal = { "id": self.goal_id, "title": self.title, + "tasks": self.tasks } return goal diff --git a/app/models/task.py b/app/models/task.py index 340e36ffc..c8adcee58 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -6,6 +6,8 @@ class Task(db.Model): title = db.Column(db.String) description = db.Column(db.Text) completed_at = db.Column(db.DateTime, nullable=True, default=None) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id')) + goal = db.relationship("Goal", back_populates="tasks") def to_dict(self): task = { @@ -16,4 +18,10 @@ def to_dict(self): } if self.completed_at is not None: task["is_complete"] = True - return task \ No newline at end of file + return task + + @classmethod + def from_dict(cls, task_data): + new_task = Task(title=task_data["title"], + description=task_data["description"]) + return new_task \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 383813366..3cdd52109 100644 --- a/app/routes.py +++ b/app/routes.py @@ -10,6 +10,7 @@ SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN") task_bp = Blueprint("task", __name__, url_prefix="/tasks") goal_bp = Blueprint("goal", __name__, url_prefix="/goals") +goal_task_bp = Blueprint("goal_task", __name__, url_prefix="/goals//tasks") diff --git a/migrations/versions/374d64514e06_.py b/migrations/versions/374d64514e06_.py new file mode 100644 index 000000000..bf663fea6 --- /dev/null +++ b/migrations/versions/374d64514e06_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 374d64514e06 +Revises: bbd0dc823856 +Create Date: 2023-08-16 20:48:16.082909 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '374d64514e06' +down_revision = 'bbd0dc823856' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'task', 'goal', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### From 3a05c1349b5bc6f2dfc4249c25b9deabdd082a9a Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 21:02:45 -0700 Subject: [PATCH 26/32] Refactor routes into folder --- app/__init__.py | 4 +- app/models/goal.py | 3 +- app/routes/__init__.py | 0 app/routes/goal_routes.py | 69 ++++++++++++++++++++++++ app/{routes.py => routes/task_routes.py} | 69 ------------------------ 5 files changed, 72 insertions(+), 73 deletions(-) create mode 100644 app/routes/__init__.py create mode 100644 app/routes/goal_routes.py rename app/{routes.py => routes/task_routes.py} (62%) diff --git a/app/__init__.py b/app/__init__.py index 0c3d11930..fa70fc4bc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,9 +30,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from .routes import task_bp, goal_bp, goal_task_bp + from .routes.task_routes import task_bp app.register_blueprint(task_bp) + from .routes.goal_routes import goal_bp app.register_blueprint(goal_bp) - app.register_blueprint(goal_task_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 674188419..258d9d751 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -9,7 +9,6 @@ class Goal(db.Model): def to_dict(self): goal = { "id": self.goal_id, - "title": self.title, - "tasks": self.tasks + "title": self.title } return goal diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py new file mode 100644 index 000000000..2c0154763 --- /dev/null +++ b/app/routes/goal_routes.py @@ -0,0 +1,69 @@ +from flask import abort, Blueprint, jsonify, make_response, request +from sqlalchemy import desc, asc +from app import db +from app.models.goal import Goal + + +goal_bp = Blueprint("goal", __name__, url_prefix="/goals") + + +@goal_bp.route("", methods=["POST"]) +def create_new_goal(): + request_body = request.get_json() + try: + new_goal = Goal( + title=request_body["title"], + ) + except KeyError: + return {"details": "Invalid data"}, 400 + + db.session.add(new_goal) + db.session.commit() + + return {"goal": new_goal.to_dict()}, 201 + + +@goal_bp.route("", methods=["GET"]) +def get_all_goals(): + sort_query = request.args.get("sort") + if sort_query == "asc": + goals = Goal.query.order_by(asc(Goal.title)) + elif sort_query == "desc": + goals = Goal.query.order_by(desc(Goal.title)) + else: + goals = Goal.query.all() + + response = [] + for goal in goals: + response.append(goal.to_dict()) + + return jsonify(response), 200 + + +@goal_bp.route("/", methods=["GET"]) +def get_one_goal(goal_id): + goal = Goal.query.get_or_404(goal_id) + return {"goal": goal.to_dict()}, 200 + + +@goal_bp.route("/", methods=["PUT"]) +def update_one_goal(goal_id): + goal = Goal.query.get_or_404(goal_id) + request_body = request.get_json() + + goal.title = request_body["title"] + + db.session.commit() + + return {"goal": goal.to_dict()}, 200 + + +@goal_bp.route("/", methods=["DELETE"]) +def delete_one_goal(goal_id): + goal = Goal.query.get_or_404(goal_id) + + db.session.delete(goal) + db.session.commit() + + return {"details": (f'Goal {goal.goal_id} "{goal.title}" ' + 'successfully deleted')}, 200 \ No newline at end of file diff --git a/app/routes.py b/app/routes/task_routes.py similarity index 62% rename from app/routes.py rename to app/routes/task_routes.py index 3cdd52109..0b8d1621d 100644 --- a/app/routes.py +++ b/app/routes/task_routes.py @@ -2,16 +2,12 @@ from sqlalchemy import desc, asc from app import db from app.models.task import Task -from app.models.goal import Goal from datetime import datetime, timezone import requests import os SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN") task_bp = Blueprint("task", __name__, url_prefix="/tasks") -goal_bp = Blueprint("goal", __name__, url_prefix="/goals") -goal_task_bp = Blueprint("goal_task", __name__, url_prefix="/goals//tasks") - def call_slack_API(title): @@ -23,8 +19,6 @@ def call_slack_API(title): return None -''' TASK ROUTES ''' - @task_bp.route("", methods=["GET"]) def get_all_tasks(): sort_query = request.args.get("sort") @@ -109,67 +103,4 @@ def delete_one_task(task_id): db.session.commit() return {"details": (f'Task {task.task_id} "{task.title}" ' - 'successfully deleted')}, 200 - - -''' GOAL ROUTES ''' -@goal_bp.route("", methods=["POST"]) -def create_new_goal(): - request_body = request.get_json() - try: - new_goal = Goal( - title=request_body["title"], - ) - except KeyError: - return {"details": "Invalid data"}, 400 - - db.session.add(new_goal) - db.session.commit() - - return {"goal": new_goal.to_dict()}, 201 - - -@goal_bp.route("", methods=["GET"]) -def get_all_goals(): - sort_query = request.args.get("sort") - if sort_query == "asc": - goals = Goal.query.order_by(asc(Goal.title)) - elif sort_query == "desc": - goals = Goal.query.order_by(desc(Goal.title)) - else: - goals = Goal.query.all() - - response = [] - for goal in goals: - response.append(goal.to_dict()) - - return jsonify(response), 200 - - -@goal_bp.route("/", methods=["GET"]) -def get_one_goal(goal_id): - goal = Goal.query.get_or_404(goal_id) - return {"goal": goal.to_dict()}, 200 - - -@goal_bp.route("/", methods=["PUT"]) -def update_one_goal(goal_id): - goal = Goal.query.get_or_404(goal_id) - request_body = request.get_json() - - goal.title = request_body["title"] - - db.session.commit() - - return {"goal": goal.to_dict()}, 200 - - -@goal_bp.route("/", methods=["DELETE"]) -def delete_one_goal(goal_id): - goal = Goal.query.get_or_404(goal_id) - - db.session.delete(goal) - db.session.commit() - - return {"details": (f'Goal {goal.goal_id} "{goal.title}" ' 'successfully deleted')}, 200 \ No newline at end of file From 2d410438e08bf286d1a795f05e74e26992baa8ef Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 22:02:32 -0700 Subject: [PATCH 27/32] Begin nested routes. Create goal_task route file. --- app/models/goal.py | 2 +- app/models/task.py | 2 +- app/routes/goal_task_routes.py | 19 +++++++++++++++++++ app/routes/task_routes.py | 19 ++++++++----------- tests/test_wave_06.py | 1 - 5 files changed, 29 insertions(+), 14 deletions(-) create mode 100644 app/routes/goal_task_routes.py diff --git a/app/models/goal.py b/app/models/goal.py index 258d9d751..d7c5864a1 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,7 +4,7 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) - tasks = db.relationship("Task", back_populates="goal") + tasks = db.relationship("Task", back_populates="goal", lazy=True) def to_dict(self): goal = { diff --git a/app/models/task.py b/app/models/task.py index c8adcee58..c6924c99e 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -6,7 +6,7 @@ class Task(db.Model): title = db.Column(db.String) description = db.Column(db.Text) completed_at = db.Column(db.DateTime, nullable=True, default=None) - goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id')) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) goal = db.relationship("Goal", back_populates="tasks") def to_dict(self): diff --git a/app/routes/goal_task_routes.py b/app/routes/goal_task_routes.py new file mode 100644 index 000000000..da9fcfcb7 --- /dev/null +++ b/app/routes/goal_task_routes.py @@ -0,0 +1,19 @@ +from flask import abort, Blueprint, jsonify, make_response, request +from sqlalchemy import desc, asc +from app import db +from app.models.goal import Goal +from app.models.task import Task +from app.routes.goal_routes import goal_bp +from datetime import datetime, timezone +import requests +import os + + +@goal_bp.route("//tasks", methods=["POST"]) +def post_task_ids_to_goal(goal_id): + request_body = request.get_json() + goal = Goal.query.get_or_404(goal_id) + + db.session.commit() + + return {"id": goal_id, "task_ids": "goal.tasks"}, 200 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 0b8d1621d..7f4865ad5 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -20,7 +20,7 @@ def call_slack_API(title): @task_bp.route("", methods=["GET"]) -def get_all_tasks(): +def get_tasks(): sort_query = request.args.get("sort") if sort_query == "asc": tasks = Task.query.order_by(asc(Task.title)) @@ -37,19 +37,16 @@ def get_all_tasks(): @task_bp.route("/", methods=["GET"]) -def get_one_task(task_id): +def get_task(task_id): task = Task.query.get_or_404(task_id) return {"task": task.to_dict()}, 200 @task_bp.route("", methods=["POST"]) -def create_new_task(): +def create_task(): request_body = request.get_json() try: - new_task = Task( - title=request_body["title"], - description=request_body["description"] - ) + new_task = Task.from_dict(request_body) except KeyError: return {"details": "Invalid data"}, 400 @@ -60,7 +57,7 @@ def create_new_task(): @task_bp.route("/", methods=["PUT"]) -def update_one_task(task_id): +def update_task(task_id): task = Task.query.get_or_404(task_id) request_body = request.get_json() @@ -73,7 +70,7 @@ def update_one_task(task_id): @task_bp.route("//mark_complete", methods=["PATCH"]) -def mark_complete_one_task(task_id): +def mark_complete(task_id): task = Task.query.get_or_404(task_id) task.completed_at = datetime.now(timezone.utc) @@ -85,7 +82,7 @@ def mark_complete_one_task(task_id): @task_bp.route("//mark_incomplete", methods=["PATCH"]) -def mark_incomplete_one_task(task_id): +def mark_incomplete(task_id): task = Task.query.get_or_404(task_id) task.completed_at = None @@ -96,7 +93,7 @@ def mark_incomplete_one_task(task_id): @task_bp.route("/", methods=["DELETE"]) -def delete_one_task(task_id): +def delete_task(task_id): task = Task.query.get_or_404(task_id) db.session.delete(task) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..4bcdebbbe 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,7 +2,6 @@ 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): # Act response = client.post("/goals/1/tasks", json={ From c8205f9d8a460097a0bfb837aebbecdfb1227c13 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 23:21:26 -0700 Subject: [PATCH 28/32] Add POST and GET nested routes --- app/__init__.py | 2 ++ app/routes/goal_task_routes.py | 32 ++++++++++++++++++++++++++++---- app/routes/task_routes.py | 2 +- tests/test_wave_06.py | 9 +-------- 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index fa70fc4bc..1ec9c0c6a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -34,5 +34,7 @@ def create_app(test_config=None): app.register_blueprint(task_bp) from .routes.goal_routes import goal_bp app.register_blueprint(goal_bp) + from .routes.goal_task_routes import goal_task_bp + app.register_blueprint(goal_task_bp) return app diff --git a/app/routes/goal_task_routes.py b/app/routes/goal_task_routes.py index da9fcfcb7..14d5e00ec 100644 --- a/app/routes/goal_task_routes.py +++ b/app/routes/goal_task_routes.py @@ -3,17 +3,41 @@ from app import db from app.models.goal import Goal from app.models.task import Task -from app.routes.goal_routes import goal_bp from datetime import datetime, timezone import requests import os -@goal_bp.route("//tasks", methods=["POST"]) +goal_task_bp = Blueprint("goal_task", __name__, url_prefix="/goals") + + +@goal_task_bp.route("//tasks", methods=["POST"]) def post_task_ids_to_goal(goal_id): request_body = request.get_json() goal = Goal.query.get_or_404(goal_id) - + + for id in request_body["task_ids"]: + task = Task.query.get_or_404(id) + task.goal = goal + + db.session.commit() + + return {"id": int(goal_id), "task_ids": request_body["task_ids"]}, 200 + + +@goal_task_bp.route("//tasks", methods=["GET"]) +def get_tasks_for_goal(goal_id): + request_body = request.get_json() + goal = Goal.query.get_or_404(goal_id) + + response = goal.to_dict() + + if not goal.tasks: + response["tasks"] = [] + + for task in goal.tasks: + response["tasks"].append(task.to_dict()) + db.session.commit() - return {"id": goal_id, "task_ids": "goal.tasks"}, 200 + return jsonify(response), 200 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 7f4865ad5..7a6c0cdef 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -73,7 +73,7 @@ def update_task(task_id): def mark_complete(task_id): task = Task.query.get_or_404(task_id) - task.completed_at = datetime.now(timezone.utc) + task.completed_at = str(datetime.now(timezone.utc)) call_slack_API(task.title) db.session.commit() diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 4bcdebbbe..06506a40f 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -22,7 +22,6 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(Goal.query.get(1).tasks) == 3 -@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={ @@ -41,7 +40,6 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on assert len(Goal.query.get(1).tasks) == 2 -@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") @@ -49,14 +47,9 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert not 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") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") From 84778a59463b249ab8ca78fbfe63d8a038218799 Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 23:31:26 -0700 Subject: [PATCH 29/32] Add GET tasks for goal and refactor task to_dict to include goal_id --- app/models/task.py | 4 +++- app/routes/goal_task_routes.py | 5 +---- tests/test_wave_06.py | 2 -- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index c6924c99e..f585c09aa 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -14,10 +14,12 @@ def to_dict(self): "id": self.task_id, "title": self.title, "description": self.description, - "is_complete": False + "is_complete": False, } if self.completed_at is not None: task["is_complete"] = True + if self.goal_id is not None: + task["goal_id"] = self.goal_id return task @classmethod diff --git a/app/routes/goal_task_routes.py b/app/routes/goal_task_routes.py index 14d5e00ec..be65f2790 100644 --- a/app/routes/goal_task_routes.py +++ b/app/routes/goal_task_routes.py @@ -31,10 +31,7 @@ def get_tasks_for_goal(goal_id): goal = Goal.query.get_or_404(goal_id) response = goal.to_dict() - - if not goal.tasks: - response["tasks"] = [] - + response["tasks"] = [] for task in goal.tasks: response["tasks"].append(task.to_dict()) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 06506a40f..daf1a5a0a 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -66,7 +66,6 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@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") @@ -91,7 +90,6 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json() From 25662a6dd1000ccc9986826d1695b4b99a538ffd Mon Sep 17 00:00:00 2001 From: jasmine Date: Wed, 16 Aug 2023 23:36:13 -0700 Subject: [PATCH 30/32] Remove unused imports. Move Slack API call back inside PATCH. --- app/routes/goal_routes.py | 2 +- app/routes/goal_task_routes.py | 6 +----- app/routes/task_routes.py | 20 ++++++++------------ 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 2c0154763..2d513fe18 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, jsonify, make_response, request +from flask import Blueprint, jsonify, request from sqlalchemy import desc, asc from app import db from app.models.goal import Goal diff --git a/app/routes/goal_task_routes.py b/app/routes/goal_task_routes.py index be65f2790..372617eaa 100644 --- a/app/routes/goal_task_routes.py +++ b/app/routes/goal_task_routes.py @@ -1,11 +1,7 @@ -from flask import abort, Blueprint, jsonify, make_response, request -from sqlalchemy import desc, asc +from flask import Blueprint, jsonify, request from app import db from app.models.goal import Goal from app.models.task import Task -from datetime import datetime, timezone -import requests -import os goal_task_bp = Blueprint("goal_task", __name__, url_prefix="/goals") diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 7a6c0cdef..5dc2ab0e6 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, jsonify, make_response, request +from flask import Blueprint, jsonify, request from sqlalchemy import desc, asc from app import db from app.models.task import Task @@ -6,17 +6,8 @@ import requests import os -SLACK_API_TOKEN = os.environ.get("SLACK_API_TOKEN") -task_bp = Blueprint("task", __name__, url_prefix="/tasks") - -def call_slack_API(title): - r = requests.post('https://slack.com/api/chat.postMessage', - data={ - 'channel': 'C05N61M2JHG', - 'text': f'Task {title} was marked complete!'}, - headers={'Authorization': SLACK_API_TOKEN}) - return None +task_bp = Blueprint("task", __name__, url_prefix="/tasks") @task_bp.route("", methods=["GET"]) @@ -74,7 +65,12 @@ def mark_complete(task_id): task = Task.query.get_or_404(task_id) task.completed_at = str(datetime.now(timezone.utc)) - call_slack_API(task.title) + + slack_bot = requests.post('https://slack.com/api/chat.postMessage', + data={ + 'channel': 'C05N61M2JHG', + 'text': f'Task "{task.title}" was marked complete!'}, + headers={'Authorization': os.environ.get("SLACK_API_TOKEN")}) db.session.commit() From 4f447021776173cfcf6b94d90ed3e48783bf16bb Mon Sep 17 00:00:00 2001 From: jasmine Date: Thu, 17 Aug 2023 01:19:12 -0700 Subject: [PATCH 31/32] Freeze requirements --- requirements.txt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index 453f0ef6a..fefdfc842 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,11 +1,12 @@ alembic==1.5.4 -attrs==20.3.0 +attrs==21.2.0 autopep8==1.5.5 -blinker==1.4 certifi==2020.12.5 chardet==4.0.0 +charset-normalizer==3.1.0 click==7.1.2 Flask==1.1.2 +Flask-Cors==3.0.10 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 gunicorn==20.1.0 @@ -22,7 +23,6 @@ py==1.11.0 pycodestyle==2.6.0 pyparsing==2.4.7 pytest==7.1.1 -pytest-cov==2.12.1 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 @@ -30,5 +30,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 -urllib3==1.26.5 +tomli==2.0.1 +urllib3==1.26.4 Werkzeug==1.0.1 From 0d7eaadacf2baf3ea68a09198315eab4ba43cb60 Mon Sep 17 00:00:00 2001 From: jasmine Date: Thu, 17 Aug 2023 11:53:16 -0700 Subject: [PATCH 32/32] Add Render Database URI --- app/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 1ec9c0c6a..7e5931242 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,8 +15,9 @@ def create_app(test_config=None): app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if test_config is None: - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + # app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + # "SQLALCHEMY_DATABASE_URI") + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("RENDER_DATABASE_URI") else: app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(