From be2a08cfea7c8c6e737cc4caf443b3d5d78f2687 Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 18:09:12 -0500 Subject: [PATCH 01/10] get, post, and put --- app/__init__.py | 2 + app/models/task.py | 31 +++++++++- app/routes.py | 66 +++++++++++++++++++- migrations/README | 1 + migrations/alembic.ini | 50 +++++++++++++++ migrations/env.py | 91 ++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++ migrations/versions/601bb9264297_.py | 40 ++++++++++++ migrations/versions/d0dcc64964c0_.py | 39 ++++++++++++ migrations/versions/e68f13a3e02c_.py | 30 +++++++++ migrations/versions/e6ece79aaff4_.py | 30 +++++++++ tests/test_wave_01.py | 21 ++++--- 12 files changed, 413 insertions(+), 12 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/601bb9264297_.py create mode 100644 migrations/versions/d0dcc64964c0_.py create mode 100644 migrations/versions/e68f13a3e02c_.py create mode 100644 migrations/versions/e6ece79aaff4_.py diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..14b242cca 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 app.routes import task_bp + app.register_blueprint(task_bp) return app diff --git a/app/models/task.py b/app/models/task.py index c91ab281f..7a94f1160 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -2,4 +2,33 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + __tablename__ = 'tasks' + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + is_complete = False + completed_at = None + + def to_dict(self): + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete) + + @classmethod + def from_dict(cls, data_dict): + return cls( + title=data_dict["title"], + description=data_dict["description"] + ) + + def replace_details(self, data_dict): + self.title=data_dict["title"] + self.description=data_dict["description"] + return self.to_dict() + + def mark_done(self): + self.is_complete = True + self.completed_at = db.func.current_timestamp() + return self.completed_at diff --git a/app/routes.py b/app/routes.py index 3aae38d49..d2bda24e1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1 +1,65 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, jsonify, make_response, request, abort +from app import db +from app.models.task import Task + +task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + +def make_task_safely(data_dict): + try: + return Task.from_dict(data_dict) + except KeyError as err: + error_message(f"Missing key: {err}", 400) + +def update_task_safely(task, data_dict): + try: + return task.replace_details(data_dict) + except KeyError as err: + error_message(f"Missing key: {err}", 400) + +def validate_task_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + task = Task.query.get(id) + if task: + return task + error_message(f"No task with ID {id}. SORRY.", 404) + +@task_bp.route("", methods=["POST"]) +def add_task(): + request_body = request.get_json() + new_task=make_task_safely(request_body) + + db.session.add(new_task) + db.session.commit() + + task_response = {"task":new_task.to_dict()} + + return jsonify(task_response), 201 + +@task_bp.route("", methods=["GET"]) +def get_tasks(): + tasks = Task.query.all() + + result_list = [task.to_dict() for task in tasks] + return jsonify(result_list) + +@task_bp.route("/", methods=["GET"]) +def get_task_by_id(id): + task = validate_task_id(id) + result = {"task": task.to_dict()} + return jsonify(result) + +@task_bp.route("", methods=["PUT"]) +def update_task(id): + task = validate_task_id(id) + request_body = request.get_json() + updated_task = update_task_safely(task, request_body) + + db.session.commit() + + return jsonify({"task":updated_task}) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..68feded2a --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,91 @@ +from __future__ import with_statement + +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') + +# 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.get_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 = current_app.extensions['migrate'].db.get_engine() + + 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"} diff --git a/migrations/versions/601bb9264297_.py b/migrations/versions/601bb9264297_.py new file mode 100644 index 000000000..c5055c930 --- /dev/null +++ b/migrations/versions/601bb9264297_.py @@ -0,0 +1,40 @@ +"""empty message + +Revision ID: 601bb9264297 +Revises: +Create Date: 2022-05-06 17:00:00.294882 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '601bb9264297' +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(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('is_complete', sa.Boolean(), 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 ### diff --git a/migrations/versions/d0dcc64964c0_.py b/migrations/versions/d0dcc64964c0_.py new file mode 100644 index 000000000..bc348aa8c --- /dev/null +++ b/migrations/versions/d0dcc64964c0_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: d0dcc64964c0 +Revises: e6ece79aaff4 +Create Date: 2022-05-07 17:01:14.880507 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd0dcc64964c0' +down_revision = 'e6ece79aaff4' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('tasks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('task') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('task', + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('id', sa.INTEGER(), autoincrement=False, nullable=False) + ) + op.drop_table('tasks') + # ### end Alembic commands ### diff --git a/migrations/versions/e68f13a3e02c_.py b/migrations/versions/e68f13a3e02c_.py new file mode 100644 index 000000000..0315f25cf --- /dev/null +++ b/migrations/versions/e68f13a3e02c_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e68f13a3e02c +Revises: 601bb9264297 +Create Date: 2022-05-06 18:34:42.221057 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e68f13a3e02c' +down_revision = '601bb9264297' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False)) + op.drop_column('task', 'task_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('task', 'id') + # ### end Alembic commands ### diff --git a/migrations/versions/e6ece79aaff4_.py b/migrations/versions/e6ece79aaff4_.py new file mode 100644 index 000000000..197013b21 --- /dev/null +++ b/migrations/versions/e6ece79aaff4_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e6ece79aaff4 +Revises: e68f13a3e02c +Create Date: 2022-05-07 16:58:41.889535 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'e6ece79aaff4' +down_revision = 'e68f13a3e02c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('task', 'completed_at') + op.drop_column('task', 'is_complete') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('is_complete', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + # ### end Alembic commands ### diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..e7ce0057a 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,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") @@ -13,7 +13,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") @@ -32,7 +32,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -51,7 +51,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") @@ -59,14 +59,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 == {"details":"No task with ID 1. SORRY."} + # 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={ @@ -93,7 +93,7 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -119,7 +119,7 @@ def test_update_task(client, one_task): assert 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_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -130,8 +130,9 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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 1d348feabd066c2c75350b431e63fe89108cfe3f Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 18:45:27 -0500 Subject: [PATCH 02/10] wave 1 passed --- app/routes.py | 14 +++++++++++--- tests/test_wave_01.py | 11 ++++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/app/routes.py b/app/routes.py index d2bda24e1..319a01557 100644 --- a/app/routes.py +++ b/app/routes.py @@ -11,13 +11,13 @@ def make_task_safely(data_dict): try: return Task.from_dict(data_dict) except KeyError as err: - error_message(f"Missing key: {err}", 400) + error_message(f"Invalid data", 400) def update_task_safely(task, data_dict): try: return task.replace_details(data_dict) except KeyError as err: - error_message(f"Missing key: {err}", 400) + error_message(f"Invalid data", 400) def validate_task_id(id): try: @@ -62,4 +62,12 @@ def update_task(id): db.session.commit() - return jsonify({"task":updated_task}) \ No newline at end of file + return jsonify({"task":updated_task}) + +@task_bp.route("", methods=["DELETE"]) +def delete_task(id): + task = validate_task_id(id) + db.session.delete(task) + db.session.commit() + + return jsonify({"details":f'Task {id} "{task.title}" successfully deleted'}) \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index e7ce0057a..65b1c1448 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -138,7 +138,7 @@ def test_update_task_not_found(client): # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -153,7 +153,7 @@ def test_delete_task(client, one_task): assert Task.query.get(1) == 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") @@ -161,8 +161,9 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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*************** # ***************************************************************** @@ -170,7 +171,7 @@ def test_delete_task_not_found(client): assert Task.query.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={ @@ -187,7 +188,7 @@ def test_create_task_must_contain_title(client): assert Task.query.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 95466c800a5268af518edc1af63fb79a3a973ae5 Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 18:56:53 -0500 Subject: [PATCH 03/10] wave 2 passed --- app/routes.py | 9 ++++++++- tests/test_wave_02.py | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 319a01557..65860472d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, jsonify, make_response, request, abort from app import db from app.models.task import Task +from sqlalchemy import desc task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") @@ -43,7 +44,13 @@ def add_task(): @task_bp.route("", methods=["GET"]) def get_tasks(): - tasks = Task.query.all() + sort_param = request.args.get("sort") + if sort_param == "asc": + tasks = Task.query.order_by("title") + elif sort_param == "desc": + tasks = Task.query.order_by(desc(Task.title)) + else: + tasks = Task.query.all() result_list = [task.to_dict() for task in tasks] return jsonify(result_list) 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 218136d5623d13fcb5f54aeeb061843503e20f90 Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 19:44:48 -0500 Subject: [PATCH 04/10] wave 3 passed --- app/models/task.py | 29 ++++++++++++++++++++++----- app/routes.py | 20 ++++++++++++++++++- migrations/versions/e66361cb0cb1_.py | 30 ++++++++++++++++++++++++++++ tests/test_wave_03.py | 22 ++++++++++---------- 4 files changed, 85 insertions(+), 16 deletions(-) create mode 100644 migrations/versions/e66361cb0cb1_.py diff --git a/app/models/task.py b/app/models/task.py index 7a94f1160..cd3f37495 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,3 +1,4 @@ +import datetime from app import db @@ -6,8 +7,8 @@ class Task(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) description = db.Column(db.String) - is_complete = False - completed_at = None + is_complete = db.Column(db.Boolean, default=False) + completed_at = db.Column(db.DateTime) def to_dict(self): return dict( @@ -18,7 +19,15 @@ def to_dict(self): @classmethod def from_dict(cls, data_dict): - return cls( + if "completed_at" in data_dict: + return cls( + title=data_dict["title"], + description=data_dict["description"], + is_complete=True, + completed_at=data_dict["completed_at"] + ) + else: + return cls( title=data_dict["title"], description=data_dict["description"] ) @@ -26,9 +35,19 @@ def from_dict(cls, data_dict): def replace_details(self, data_dict): self.title=data_dict["title"] self.description=data_dict["description"] + self.is_complete=False + if "completed_at" in data_dict: + self.completed_at=data_dict["completed_at"] + self.is_complete=True return self.to_dict() def mark_done(self): self.is_complete = True - self.completed_at = db.func.current_timestamp() - return self.completed_at + current_time = datetime.datetime.now() + self.completed_at = current_time + return self.to_dict() + + def mark_not_done(self): + self.is_complete = False + self.completed_at = None + return self.to_dict() \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 65860472d..e2fcbdca7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -77,4 +77,22 @@ def delete_task(id): db.session.delete(task) db.session.commit() - return jsonify({"details":f'Task {id} "{task.title}" successfully deleted'}) \ No newline at end of file + return jsonify({"details":f'Task {id} "{task.title}" successfully deleted'}) + +@task_bp.route("/mark_complete", methods=["PATCH"]) +def mark_complete(id): + task = validate_task_id(id) + updated_task = task.mark_done() + + db.session.commit() + + return jsonify({"task":updated_task}) + +@task_bp.route("/mark_incomplete", methods=["PATCH"]) +def mark_incomplete(id): + task = validate_task_id(id) + updated_task = task.mark_not_done() + + db.session.commit() + + return jsonify({"task":updated_task}) \ No newline at end of file diff --git a/migrations/versions/e66361cb0cb1_.py b/migrations/versions/e66361cb0cb1_.py new file mode 100644 index 000000000..b37cea978 --- /dev/null +++ b/migrations/versions/e66361cb0cb1_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e66361cb0cb1 +Revises: d0dcc64964c0 +Create Date: 2022-05-07 19:28:12.900453 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e66361cb0cb1' +down_revision = 'd0dcc64964c0' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('tasks', sa.Column('completed_at', sa.DateTime(), nullable=True)) + op.add_column('tasks', sa.Column('is_complete', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('tasks', 'is_complete') + op.drop_column('tasks', 'completed_at') + # ### end Alembic commands ### diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 959176ceb..72fc0b4cb 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,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 """ @@ -42,7 +42,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") +# @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 +62,7 @@ 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") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +99,7 @@ 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") +# @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 +119,7 @@ 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") +# @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 +127,15 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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 pytfeature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +143,9 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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*************** # ***************************************************************** @@ -151,7 +153,7 @@ def test_mark_incomplete_missing_task(client): # Let's add this test for creating tasks, now that # the completion functionality has been implemented -@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_with_valid_completed_at(client): # Act response = client.post("/tasks", json={ @@ -181,7 +183,7 @@ def test_create_task_with_valid_completed_at(client): # Let's add this test for updating tasks, now that # the completion functionality has been implemented -@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_with_completed_at_date(client, completed_task): # Act response = client.put("/tasks/1", json={ From 5a667b735c4cb70c3acc8bb0037d9e2de27b33dd Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 20:50:27 -0500 Subject: [PATCH 05/10] wave 4 passed --- ada-project-docs/wave_04.md | 40 +++++++++++++++++++++++++++++++++++++ app/routes.py | 10 +++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/ada-project-docs/wave_04.md b/ada-project-docs/wave_04.md index 079ce6485..f06160a76 100644 --- a/ada-project-docs/wave_04.md +++ b/ada-project-docs/wave_04.md @@ -98,9 +98,13 @@ Visit https://api.slack.com/methods/chat.postMessage to read about the Slack API Answer the following questions. These questions will help you become familiar with the API, and make working with it easier. - What is the responsibility of this endpoint? + - post a message on a channel in slack - What is the URL and HTTP method for this endpoint? + - https://slack.com/api/chat.postMessage?channel=&text=& - What are the _two_ _required_ arguments for this endpoint? + - token, channel - How does this endpoint relate to the Slackbot API key (token) we just created? + - I'm assuming we will use this endpoint to send messages about whether or not the tasks have been done Now, visit https://api.slack.com/methods/chat.postMessage/test. @@ -119,8 +123,42 @@ Press the "Test Method" button! Scroll down to see the HTTP response. Answer the following questions: - Did we get a success message? If so, did we see the message in our actual Slack workspace? + - we got ok:True? And yes, we saw a message in our actual slack workspace - Did we get an error emssage? If so, why? + - No... - What is the shape of this JSON? Is it a JSON object or array? What keys and values are there? + - {"ok":, + - "channel":, + - "ts": a string of numbers? Is this an IP?, + - "message"{ + - "bot_id": string, + - "type": "message", + - "text": , + - "user": string, + - "ts": same as before under ts?, + - "app_id": string of caps and nums, + - "team": another string of caps and nums, + - "bot_profile":{ + - "id": same as bot_id, + - "app_id":same as app_id before, + - "name": , + - "icons": { + - "image_36": url, + - "image_48": url, + - "image_72": url + - }, + - "deleted": boolean, + - "updated": a number, + - "team_id": same as team + - }, + - "blocks":[ + - {"type": "rich_text", + - "block_id": "PTh", + - "elements": [ + - {"type":"rich_text_section", + - "elements":[ + - {"type":"text", + - "text": text body}]}]}]}} ### Verify with Postman @@ -139,6 +177,8 @@ Open Postman and make a request that mimics the API call to Slack that we just t - In "Headers," add this new key-value pair: - `Authorization`: `"Bearer xoxb-150..."`, where `xoxb-150...` is your full Slackbot token +--> DO NOT INCLUDE ANY QUOTES <---- + ![](assets/postman_test_headers.png) Press "Send" and see the Slack message come through! diff --git a/app/routes.py b/app/routes.py index e2fcbdca7..dda2670ac 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,6 +2,8 @@ from app import db from app.models.task import Task from sqlalchemy import desc +import requests +import os task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") @@ -85,6 +87,7 @@ def mark_complete(id): updated_task = task.mark_done() db.session.commit() + send_slack_message(f"Someone just completed the task {task.title}") return jsonify({"task":updated_task}) @@ -95,4 +98,9 @@ def mark_incomplete(id): db.session.commit() - return jsonify({"task":updated_task}) \ No newline at end of file + return jsonify({"task":updated_task}) + +def send_slack_message(message): + Slack_Key = os.environ.get("Slack_API_Token") + requests.post('https://slack.com/api/chat.postMessage', params={'text':message, 'channel':'task-notifications'}, headers={'Authorization':Slack_Key}) + return True \ No newline at end of file From 982d96903200123150dab1d6404023f5ace84f4d Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sat, 7 May 2022 21:16:58 -0500 Subject: [PATCH 06/10] wave 5 passed --- app/__init__.py | 5 +- app/models/goal.py | 14 +++ app/routes/__init__.py | 0 app/routes/goal_routes.py | 106 +++++++++++++++++++++++ app/{routes.py => routes/task_routes.py} | 0 migrations/versions/bc641ad71a61_.py | 28 ++++++ tests/test_wave_05.py | 57 ++++++++---- 7 files changed, 193 insertions(+), 17 deletions(-) create mode 100644 app/routes/__init__.py create mode 100644 app/routes/goal_routes.py rename app/{routes.py => routes/task_routes.py} (100%) create mode 100644 migrations/versions/bc641ad71a61_.py diff --git a/app/__init__.py b/app/__init__.py index 14b242cca..691fa6a1a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,7 +30,10 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from app.routes import task_bp + from app.routes.task_routes import task_bp app.register_blueprint(task_bp) + from app.routes.goal_routes import goal_bp + app.register_blueprint(goal_bp) + return app diff --git a/app/models/goal.py b/app/models/goal.py index b0ed11dd8..5d1ff5fc4 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,17 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + + def to_dict(self): + return dict( + id=self.goal_id, + title=self.title) + + @classmethod + def from_dict(cls, data_dict): + return cls(title=data_dict["title"]) + + def replace_details(self, data_dict): + self.title=data_dict["title"] + return self.to_dict() 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..a924748f0 --- /dev/null +++ b/app/routes/goal_routes.py @@ -0,0 +1,106 @@ +from flask import Blueprint, jsonify, make_response, request, abort +from app import db +from app.models.goal import Goal +# from sqlalchemy import desc +# import requests +# import os + +goal_bp = Blueprint("goals", __name__, url_prefix="/goals") + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + +def make_goal_safely(data_dict): + try: + return Goal.from_dict(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def update_goal_safely(goal, data_dict): + try: + return goal.replace_details(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def validate_goal_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + goal = Goal.query.get(id) + if goal: + return goal + error_message(f"No goal with ID {id}. SORRY.", 404) + +@goal_bp.route("", methods=["POST"]) +def add_goal(): + request_body = request.get_json() + new_goal=make_goal_safely(request_body) + + db.session.add(new_goal) + db.session.commit() + + task_response = {"goal":new_goal.to_dict()} + + return jsonify(task_response), 201 + +@goal_bp.route("", methods=["GET"]) +def get_goals(): +# sort_param = request.args.get("sort") +# if sort_param == "asc": +# tasks = Task.query.order_by("title") +# elif sort_param == "desc": +# tasks = Task.query.order_by(desc(Task.title)) +# else: + goals = Goal.query.all() + + result_list = [goal.to_dict() for goal in goals] + return jsonify(result_list) + +@goal_bp.route("/", methods=["GET"]) +def get_goal_by_id(id): + goal = validate_goal_id(id) + result = {"goal": goal.to_dict()} + return jsonify(result) + +@goal_bp.route("", methods=["PUT"]) +def update_goal(id): + goal = validate_goal_id(id) + request_body = request.get_json() + updated_goal = update_goal_safely(goal, request_body) + + db.session.commit() + + return jsonify({"goal":updated_goal}) + +@goal_bp.route("", methods=["DELETE"]) +def delete_goal(id): + goal = validate_goal_id(id) + db.session.delete(goal) + db.session.commit() + + return jsonify({"details":f'Goal {id} "{goal.title}" successfully deleted'}) + +# @task_bp.route("/mark_complete", methods=["PATCH"]) +# def mark_complete(id): +# task = validate_task_id(id) +# updated_task = task.mark_done() + +# db.session.commit() +# send_slack_message(f"Someone just completed the task {task.title}") + +# return jsonify({"task":updated_task}) + +# @task_bp.route("/mark_incomplete", methods=["PATCH"]) +# def mark_incomplete(id): +# task = validate_task_id(id) +# updated_task = task.mark_not_done() + +# db.session.commit() + +# return jsonify({"task":updated_task}) + +# def send_slack_message(message): +# Slack_Key = os.environ.get("Slack_API_Token") +# requests.post('https://slack.com/api/chat.postMessage', params={'text':message, 'channel':'task-notifications'}, headers={'Authorization':Slack_Key}) +# return True \ No newline at end of file diff --git a/app/routes.py b/app/routes/task_routes.py similarity index 100% rename from app/routes.py rename to app/routes/task_routes.py diff --git a/migrations/versions/bc641ad71a61_.py b/migrations/versions/bc641ad71a61_.py new file mode 100644 index 000000000..a47a8b14f --- /dev/null +++ b/migrations/versions/bc641ad71a61_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: bc641ad71a61 +Revises: e66361cb0cb1 +Create Date: 2022-05-07 21:02:23.288410 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bc641ad71a61' +down_revision = 'e66361cb0cb1' +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 ### diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..0ffce56be 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,22 +46,24 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + # raise Exception("Complete test") # Assert # ---- Complete Test ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details":"No goal with ID 1. SORRY."} # ---- 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,34 +82,52 @@ 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") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 200 # assertion 2 goes here + assert "goal" in response_body # assertion 3 goes here + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title", + } + } # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title", + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details":"No goal with ID 1. SORRY."} # ---- 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") @@ -123,28 +143,33 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + response_body=response.get_json() + assert response_body == {"details":"No goal with ID 1. SORRY."} + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details":"No goal with ID 1. SORRY."} # ---- 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 c78104e8cd21afdcebfda83fb7262778bf325f41 Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Sun, 8 May 2022 10:15:44 -0500 Subject: [PATCH 07/10] wave 6 passed --- app/models/goal.py | 30 +++++++++++++++++++- app/models/task.py | 30 ++++++++++++++------ app/routes/goal_routes.py | 22 +++++++++++++++ app/routes/task_routes.py | 6 ++-- migrations/versions/bbfd43b6d86a_.py | 42 ++++++++++++++++++++++++++++ tests/test_wave_06.py | 16 +++++------ 6 files changed, 125 insertions(+), 21 deletions(-) create mode 100644 migrations/versions/bbfd43b6d86a_.py diff --git a/app/models/goal.py b/app/models/goal.py index 5d1ff5fc4..587c2ad39 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,18 +2,46 @@ class Goal(db.Model): + __tablename__ = 'goals' goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) + tasks = db.relationship("Task", backref="goals") def to_dict(self): + task_list = [] + for task in self.tasks: + task_list.append(task.id) + if task_list: + return dict( + id=self.goal_id, + task_ids=task_list + ) return dict( id=self.goal_id, title=self.title) + def get_tasks(self): + from .task import Task + task_list = [] + for task in self.tasks: + readable_task = task.task_to_dict() + task_list.append(readable_task) + return dict( + id=self.goal_id, + title=self.title, + tasks=task_list) + @classmethod def from_dict(cls, data_dict): return cls(title=data_dict["title"]) def replace_details(self, data_dict): - self.title=data_dict["title"] + if "task_ids" in data_dict: + from .task import Task + for id in data_dict["task_ids"]: + task = Task.query.get(id) + if task not in self.tasks: + self.tasks.append(task) + else: + self.title=data_dict["title"] return self.to_dict() diff --git a/app/models/task.py b/app/models/task.py index cd3f37495..a2329d39f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,6 @@ import datetime from app import db +from app.models.goal import Goal class Task(db.Model): @@ -9,13 +10,24 @@ class Task(db.Model): description = db.Column(db.String) is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime) + goal_id = db.Column(db.Integer, db.ForeignKey(Goal.goal_id)) + # goal = db.relationship("Goal", back_populates="task") - def to_dict(self): - return dict( - id=self.id, - title=self.title, - description=self.description, - is_complete=self.is_complete) + def task_to_dict(self): + if self.goal_id: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete, + goal_id = self.goal_id + ) + else: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete) @classmethod def from_dict(cls, data_dict): @@ -39,15 +51,15 @@ def replace_details(self, data_dict): if "completed_at" in data_dict: self.completed_at=data_dict["completed_at"] self.is_complete=True - return self.to_dict() + return self.task_to_dict() def mark_done(self): self.is_complete = True current_time = datetime.datetime.now() self.completed_at = current_time - return self.to_dict() + return self.task_to_dict() def mark_not_done(self): self.is_complete = False self.completed_at = None - return self.to_dict() \ No newline at end of file + return self.task_to_dict() \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index a924748f0..8937ff95c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, jsonify, make_response, request, abort from app import db from app.models.goal import Goal +from .task_routes import validate_task_id, Task # from sqlalchemy import desc # import requests # import os @@ -81,6 +82,27 @@ def delete_goal(id): return jsonify({"details":f'Goal {id} "{goal.title}" successfully deleted'}) +@goal_bp.route("//tasks", methods=["POST"]) +def add_task_to_goal(id): + goal = validate_goal_id(id) + request_body = request.get_json() + data_dict = {"task_ids": []} + for task in request_body["task_ids"]: + validate_task_id(task) + data_dict["task_ids"].append(task) + # updated_goal = update_goal_safely(goal, request_body) + update_tasks_in_goal = update_goal_safely(goal, data_dict) + db.session.commit() + # task_response = {"goal":update_tasks_in_goal} + + return jsonify(update_tasks_in_goal), 200 + +@goal_bp.route("//tasks", methods=["GET"]) +def get_tasks_from_goal(id): + goal = validate_goal_id(id) + result = goal.get_tasks() + return jsonify(result) + # @task_bp.route("/mark_complete", methods=["PATCH"]) # def mark_complete(id): # task = validate_task_id(id) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index dda2670ac..0c816a02d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -40,7 +40,7 @@ def add_task(): db.session.add(new_task) db.session.commit() - task_response = {"task":new_task.to_dict()} + task_response = {"task":new_task.task_to_dict()} return jsonify(task_response), 201 @@ -54,13 +54,13 @@ def get_tasks(): else: tasks = Task.query.all() - result_list = [task.to_dict() for task in tasks] + result_list = [task.task_to_dict() for task in tasks] return jsonify(result_list) @task_bp.route("/", methods=["GET"]) def get_task_by_id(id): task = validate_task_id(id) - result = {"task": task.to_dict()} + result = {"task": task.task_to_dict()} return jsonify(result) @task_bp.route("", methods=["PUT"]) diff --git a/migrations/versions/bbfd43b6d86a_.py b/migrations/versions/bbfd43b6d86a_.py new file mode 100644 index 000000000..56bedc9a4 --- /dev/null +++ b/migrations/versions/bbfd43b6d86a_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: bbfd43b6d86a +Revises: bc641ad71a61 +Create Date: 2022-05-08 09:02:51.644143 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bbfd43b6d86a' +down_revision = 'bc641ad71a61' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goals', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('goal_id') + ) + op.drop_table('goal') + op.add_column('tasks', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'tasks', 'goals', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'tasks', type_='foreignkey') + op.drop_column('tasks', 'goal_id') + op.create_table('goal', + sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('goal_id', name='goal_pkey') + ) + op.drop_table('goals') + # ### end Alembic commands ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..8a6ba94f5 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -23,7 +23,7 @@ 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") +# @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={ @@ -42,7 +42,7 @@ 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") +# @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") @@ -50,14 +50,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") + assert response_body == {"details":"No goal with ID 1. SORRY."} + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -74,7 +74,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") @@ -99,7 +99,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 eeef1e02d2b767e765c1c95ae4f5f6c3269d862d Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Mon, 9 May 2022 16:46:18 -0500 Subject: [PATCH 08/10] added Procfile --- Procfile | 1 + requirements.txt | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 30ff414fe..0c1ecd619 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,12 @@ alembic==1.5.4 attrs==20.3.0 -autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.3.2 Flask==1.1.2 -Flask-Migrate==2.6.0 +Flask-Migrate==3.1.0 Flask-SQLAlchemy==2.4.4 gunicorn==20.1.0 idna==2.10 @@ -17,7 +17,7 @@ Mako==1.1.4 MarkupSafe==1.1.1 packaging==20.9 pluggy==0.13.1 -psycopg2-binary==2.8.6 +psycopg2-binary==2.9.3 py==1.10.0 pycodestyle==2.6.0 pyparsing==2.4.7 From 390032cdf8cf884b925e922b30e6e0f10d076985 Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Thu, 12 May 2022 17:08:33 -0500 Subject: [PATCH 09/10] minor cleaning --- app/models/task.py | 1 - app/routes/goal_routes.py | 35 +---------------------------------- 2 files changed, 1 insertion(+), 35 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index a2329d39f..8d024784f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,7 +11,6 @@ class Task(db.Model): is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime) goal_id = db.Column(db.Integer, db.ForeignKey(Goal.goal_id)) - # goal = db.relationship("Goal", back_populates="task") def task_to_dict(self): if self.goal_id: diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 8937ff95c..3e921f0fe 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,9 +2,6 @@ from app import db from app.models.goal import Goal from .task_routes import validate_task_id, Task -# from sqlalchemy import desc -# import requests -# import os goal_bp = Blueprint("goals", __name__, url_prefix="/goals") @@ -47,12 +44,6 @@ def add_goal(): @goal_bp.route("", methods=["GET"]) def get_goals(): -# sort_param = request.args.get("sort") -# if sort_param == "asc": -# tasks = Task.query.order_by("title") -# elif sort_param == "desc": -# tasks = Task.query.order_by(desc(Task.title)) -# else: goals = Goal.query.all() result_list = [goal.to_dict() for goal in goals] @@ -101,28 +92,4 @@ def add_task_to_goal(id): def get_tasks_from_goal(id): goal = validate_goal_id(id) result = goal.get_tasks() - return jsonify(result) - -# @task_bp.route("/mark_complete", methods=["PATCH"]) -# def mark_complete(id): -# task = validate_task_id(id) -# updated_task = task.mark_done() - -# db.session.commit() -# send_slack_message(f"Someone just completed the task {task.title}") - -# return jsonify({"task":updated_task}) - -# @task_bp.route("/mark_incomplete", methods=["PATCH"]) -# def mark_incomplete(id): -# task = validate_task_id(id) -# updated_task = task.mark_not_done() - -# db.session.commit() - -# return jsonify({"task":updated_task}) - -# def send_slack_message(message): -# Slack_Key = os.environ.get("Slack_API_Token") -# requests.post('https://slack.com/api/chat.postMessage', params={'text':message, 'channel':'task-notifications'}, headers={'Authorization':Slack_Key}) -# return True \ No newline at end of file + return jsonify(result) \ No newline at end of file From e043105cde87e6764da190db14c0d799bb0c8e5b Mon Sep 17 00:00:00 2001 From: Christina Webber Date: Thu, 12 May 2022 17:23:04 -0500 Subject: [PATCH 10/10] not returning dict --- app/models/task.py | 6 +++--- app/routes/task_routes.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 8d024784f..ee74ffb24 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -50,15 +50,15 @@ def replace_details(self, data_dict): if "completed_at" in data_dict: self.completed_at=data_dict["completed_at"] self.is_complete=True - return self.task_to_dict() + return self def mark_done(self): self.is_complete = True current_time = datetime.datetime.now() self.completed_at = current_time - return self.task_to_dict() + return self def mark_not_done(self): self.is_complete = False self.completed_at = None - return self.task_to_dict() \ No newline at end of file + return self \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 0c816a02d..08e886d0b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -71,7 +71,7 @@ def update_task(id): db.session.commit() - return jsonify({"task":updated_task}) + return jsonify({"task":updated_task.task_to_dict()}) @task_bp.route("", methods=["DELETE"]) def delete_task(id): @@ -89,7 +89,7 @@ def mark_complete(id): db.session.commit() send_slack_message(f"Someone just completed the task {task.title}") - return jsonify({"task":updated_task}) + return jsonify({"task":updated_task.task_to_dict()}) @task_bp.route("/mark_incomplete", methods=["PATCH"]) def mark_incomplete(id): @@ -98,7 +98,7 @@ def mark_incomplete(id): db.session.commit() - return jsonify({"task":updated_task}) + return jsonify({"task":updated_task.task_to_dict()}) def send_slack_message(message): Slack_Key = os.environ.get("Slack_API_Token")