From 3224d546af386fe3d034fcd1114dc9f13da9e236 Mon Sep 17 00:00:00 2001 From: Miranda Date: Wed, 2 Nov 2022 13:50:35 -0700 Subject: [PATCH 01/14] created .env file and migrations folder --- 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 76048c3fd0a0bfd98785cffb7b594d46986211a1 Mon Sep 17 00:00:00 2001 From: Miranda Date: Wed, 2 Nov 2022 14:33:39 -0700 Subject: [PATCH 02/14] created the Task Model(table), and registered the blueprint --- app/__init__.py | 3 +++ app/models/task.py | 6 ++++- app/routes.py | 8 +++++- migrations/versions/143607d7509b_.py | 38 +++++++++++++++++++++++++++ migrations/versions/50e6ba6b2899_.py | 39 ++++++++++++++++++++++++++++ 5 files changed, 92 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/143607d7509b_.py create mode 100644 migrations/versions/50e6ba6b2899_.py diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..f996a906b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,8 @@ 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..7622e6d78 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,9 @@ from app import db - +# create the table with attributes +# after created, run flask db init, flask db migrate, flask db upgrade class Task(db.Model): task_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime) diff --git a/app/routes.py b/app/routes.py index 3aae38d49..bdf79968f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1 +1,7 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint +from app import db +from app.models.task import Task + + +task_bp = Blueprint("Task_bp", __name__, url_prefix="tasks") + diff --git a/migrations/versions/143607d7509b_.py b/migrations/versions/143607d7509b_.py new file mode 100644 index 000000000..28784e845 --- /dev/null +++ b/migrations/versions/143607d7509b_.py @@ -0,0 +1,38 @@ +"""empty message + +Revision ID: 143607d7509b +Revises: 50e6ba6b2899 +Create Date: 2022-11-02 14:09:36.795693 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = '143607d7509b' +down_revision = '50e6ba6b2899' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('completed_at', sa.DateTime(), nullable=True)) + op.add_column('task', sa.Column('description', sa.String(), nullable=True)) + op.add_column('task', sa.Column('title', sa.String(), nullable=True)) + op.drop_column('task', 'task_description') + op.drop_column('task', 'task_title') + op.drop_column('task', 'task_completed_at') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('task_title', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('task_description', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.drop_column('task', 'title') + op.drop_column('task', 'description') + op.drop_column('task', 'completed_at') + # ### end Alembic commands ### diff --git a/migrations/versions/50e6ba6b2899_.py b/migrations/versions/50e6ba6b2899_.py new file mode 100644 index 000000000..c095259d9 --- /dev/null +++ b/migrations/versions/50e6ba6b2899_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 50e6ba6b2899 +Revises: +Create Date: 2022-11-02 14:07:23.594711 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '50e6ba6b2899' +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('task_title', sa.String(), nullable=True), + sa.Column('task_description', sa.String(), nullable=True), + sa.Column('task_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 f4ab1a6965f8065ae6ef494b20544388cecfe495 Mon Sep 17 00:00:00 2001 From: Miranda Date: Thu, 3 Nov 2022 23:37:44 -0700 Subject: [PATCH 03/14] finished wave 1, spent some time on the part of create_task where the completed_at type and value --- app/models/task.py | 13 ++++++- app/routes.py | 86 ++++++++++++++++++++++++++++++++++++++++++- tests/test_wave_01.py | 33 +++++++++-------- 3 files changed, 113 insertions(+), 19 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 7622e6d78..cbfda46c8 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,9 +1,18 @@ from app import db + # create the table with attributes -# after created, run flask db init, flask db migrate, flask db upgrade +# after created, flask db migrate, flask db upgrade class Task(db.Model): task_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) description = db.Column(db.String) - completed_at = db.Column(db.DateTime) + completed_at = db.Column(db.DateTime, nullable=True) + + def return_body(self): + return { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": False + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index bdf79968f..c8c7f5181 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,7 +1,89 @@ -from flask import Blueprint +from flask import Blueprint, request, make_response, jsonify, abort from app import db from app.models.task import Task +task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") -task_bp = Blueprint("Task_bp", __name__, url_prefix="tasks") +# helper function +def validate_task(task_id): + try: + task_id = int(task_id) + except ValueError: + response_str = f"Invalid task id: {task_id} must be an integer" + abort(make_response(jsonify({"message":response_str}), 400)) + matching_task = Task.query.get(task_id) + + if not matching_task: + abort(make_response(jsonify({"message": f"The {task_id} is not found"}), 404)) + + return matching_task + + +# Create a Task: Valid Task With null completed_at +@task_bp.route("", methods=["POST"]) +def create_task(): + response_body = request.get_json() + + if "title" not in response_body or\ + "description" not in response_body: + return jsonify({"details": "Invalid data"}), 400 + + new_task = Task( + title = response_body["title"], + description = response_body["description"] + ) + + db.session.add(new_task) + db.session.commit() + + return jsonify({"task":new_task.return_body()}),201 + + +# Get Tasks: Getting Saved Tasks +@task_bp.route("", methods=["GET"]) +def read_task(): + # title_param = request.args.get("title") + # if title_param is not None: + # tasks = Task.query.filter_by(title=title_param) + # else: + tasks = Task.query.all() + + read_task_result = [] + for task in tasks: + read_task_result.append(task.return_body()) + + return jsonify(read_task_result), 200 + + +# Get One Task: One Saved Task +@task_bp.route("/", methods=["GET"]) +def get_one_task_by_id(task_id): + chosen_task = validate_task(task_id) + + return jsonify({"task":chosen_task.return_body()}), 200 + + +# Update Task +@task_bp.route("/", methods=["PUT"]) +def update_task(task_id): + chosen_task = validate_task(task_id) + request_body = request.get_json() + + chosen_task.title = request_body["title"] + chosen_task.description = request_body["description"] + + db.session.commit() + return jsonify({"task":chosen_task.return_body()}), 200 + + +# Deleting a Task +@task_bp.route("/", methods=["DELETE"]) +def delete_one_task(task_id): + task_to_delete = validate_task(task_id) + + db.session.delete(task_to_delete) + db.session.commit() + + return jsonify({"details": f'Task {task_to_delete.task_id} \ + "{task_to_delete.title}" successfully deleted'}), 200 \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..a0114b785 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,15 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert "message" in response_body - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@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 +94,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 +120,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,14 +131,15 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 + assert "message" in response_body - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@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") @@ -152,7 +154,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") @@ -160,8 +162,9 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert "message" in response_body + + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -169,7 +172,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={ @@ -186,7 +189,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 c087765bf249ceab6f993fc27af95edebebd3d80 Mon Sep 17 00:00:00 2001 From: Miranda Date: Fri, 4 Nov 2022 12:07:13 -0700 Subject: [PATCH 04/14] Do the review and some tests, added comments. Found one bug still cannot solve --- app/routes.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index c8c7f5181..c04bffa12 100644 --- a/app/routes.py +++ b/app/routes.py @@ -25,34 +25,36 @@ def validate_task(task_id): def create_task(): response_body = request.get_json() + # If add "is_complete" not in respnse_body + # in postman it return 500. + # Haven't solve the problem, so I take out that line if "title" not in response_body or\ "description" not in response_body: + # "is_complete" not in respnse_body return jsonify({"details": "Invalid data"}), 400 new_task = Task( title = response_body["title"], - description = response_body["description"] + description = response_body["description"], + # completed_at = response_body["is_complete"] ) db.session.add(new_task) db.session.commit() + # using the class method in task.py return jsonify({"task":new_task.return_body()}),201 # Get Tasks: Getting Saved Tasks @task_bp.route("", methods=["GET"]) def read_task(): - # title_param = request.args.get("title") - # if title_param is not None: - # tasks = Task.query.filter_by(title=title_param) - # else: tasks = Task.query.all() read_task_result = [] - for task in tasks: - read_task_result.append(task.return_body()) - + # for task in tasks: + # read_task_result.append(task.return_body()) + read_task_result = [task.return_body() for task in tasks] return jsonify(read_task_result), 200 @@ -67,6 +69,8 @@ def get_one_task_by_id(task_id): # Update Task @task_bp.route("/", methods=["PUT"]) def update_task(task_id): + # after update the task, it becomes to the last one + # id order: 2341 chosen_task = validate_task(task_id) request_body = request.get_json() @@ -76,6 +80,7 @@ def update_task(task_id): db.session.commit() return jsonify({"task":chosen_task.return_body()}), 200 + # Deleting a Task @task_bp.route("/", methods=["DELETE"]) @@ -85,5 +90,5 @@ def delete_one_task(task_id): db.session.delete(task_to_delete) db.session.commit() - return jsonify({"details": f'Task {task_to_delete.task_id} \ - "{task_to_delete.title}" successfully deleted'}), 200 \ No newline at end of file + # mistakes in the return sentence trapped me for some time + return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 \ No newline at end of file From 1ec4112be1e9c1dd0446e0342810128bd068f11c Mon Sep 17 00:00:00 2001 From: Miranda Date: Sun, 6 Nov 2022 16:08:24 -0800 Subject: [PATCH 05/14] update the get read_task function to sorting tasks by title Ascending/descrending --- app/routes.py | 54 +++++++++++++++++++++++++++++++++++++------ tests/test_wave_02.py | 4 ++-- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index c04bffa12..d8a77212d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, request, make_response, jsonify, abort from app import db from app.models.task import Task +from sqlalchemy import asc, desc task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -49,13 +50,27 @@ def create_task(): # Get Tasks: Getting Saved Tasks @task_bp.route("", methods=["GET"]) def read_task(): - tasks = Task.query.all() + # tasks = Task.query.all() - read_task_result = [] - # for task in tasks: - # read_task_result.append(task.return_body()) - read_task_result = [task.return_body() for task in tasks] - return jsonify(read_task_result), 200 + # read_task_result = [] + # # for task in tasks: + # # read_task_result.append(task.return_body()) + # read_task_result = [task.return_body() for task in tasks] + # return jsonify(read_task_result), 200 + + sort_query = request.args.get("sort") + + if sort_query == "asc": + tasks = Task.query.order_by(Task.title.asc()) + elif sort_query == "desc": + tasks = Task.query.order_by(Task.title.desc()) + else: + tasks = Task.query.all() + + response = [] + response = [task.return_body() for task in tasks] + return jsonify(response), 200 + # Get One Task: One Saved Task @@ -91,4 +106,29 @@ def delete_one_task(task_id): db.session.commit() # mistakes in the return sentence trapped me for some time - return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 \ No newline at end of file + return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 + + + +# Sorting Tasks By Title, Ascending/Descending +# @task_bp.route("", methods=["GET"]) +# def sorting_tasks(): +# # query +# sort_query = request.args.get("sort") + +# if sort_query == "asc": +# tasks = Task.query.order_by(Task.title.aec()) +# elif sort_query == "desc": +# tasks = Task.query.order_by(Task.title.desc()) +# elif sort_query is None: +# tasks = Task.query.all() + +# response = [] +# response = [task.return_body() for task in tasks] +# return jsonify(response), 200 + + + + + + \ No newline at end of file diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..c9a76e6b1 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 4b34d84a9dfca25eb4cfa29ad2e53c3234099029 Mon Sep 17 00:00:00 2001 From: Miranda Date: Tue, 8 Nov 2022 15:11:34 -0800 Subject: [PATCH 06/14] added 2 PATCH methods to update the task complete status --- app/models/task.py | 25 ++++++++++++++++++-- app/routes.py | 53 ++++++++++++++++++++++++++----------------- tests/test_wave_03.py | 22 +++++++++--------- 3 files changed, 66 insertions(+), 34 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index cbfda46c8..200c12b62 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -14,5 +14,26 @@ def return_body(self): "id": self.task_id, "title": self.title, "description": self.description, - "is_complete": False - } \ No newline at end of file + "is_complete": self.check_complete_or_not() + } + + + def check_complete_or_not(self): + if self.completed_at: + is_complete = True + else: + is_complete = False + return is_complete + + + # @classmethod + # def from_dict(cls, data_dict): + # # cls represents all the class variables + # if "title" in data_dict and "description" in data_dict and\ + # "is_complete" in data_dict: + # new_obj = cls( + # title=data_dict["title"], + # description=data_dict["description"], + # completed_at=data_dict["is_complete"] + # ) + # return new_obj diff --git a/app/routes.py b/app/routes.py index d8a77212d..c0aa4b544 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,3 +1,4 @@ +from datetime import datetime from flask import Blueprint, request, make_response, jsonify, abort from app import db from app.models.task import Task @@ -44,10 +45,10 @@ def create_task(): db.session.commit() # using the class method in task.py - return jsonify({"task":new_task.return_body()}),201 + return jsonify({"task":new_task.return_body()}), 201 -# Get Tasks: Getting Saved Tasks +# Get Tasks: Getting Saved Tasks, sorting by ascending/descending @task_bp.route("", methods=["GET"]) def read_task(): # tasks = Task.query.all() @@ -57,7 +58,6 @@ def read_task(): # # read_task_result.append(task.return_body()) # read_task_result = [task.return_body() for task in tasks] # return jsonify(read_task_result), 200 - sort_query = request.args.get("sort") if sort_query == "asc": @@ -108,27 +108,38 @@ def delete_one_task(task_id): # mistakes in the return sentence trapped me for some time return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 + +@task_bp.route("//mark_complete", methods=["PATCH"]) +def mark_complete_update(task_id): + chosen_task = validate_task(task_id) + task = Task.query.get(task_id) + if task is None: + return make_response("The task was not found", 404) + task.completed_at = datetime.now() -# Sorting Tasks By Title, Ascending/Descending -# @task_bp.route("", methods=["GET"]) -# def sorting_tasks(): -# # query -# sort_query = request.args.get("sort") - -# if sort_query == "asc": -# tasks = Task.query.order_by(Task.title.aec()) -# elif sort_query == "desc": -# tasks = Task.query.order_by(Task.title.desc()) -# elif sort_query is None: -# tasks = Task.query.all() - -# response = [] -# response = [task.return_body() for task in tasks] -# return jsonify(response), 200 + db.session.commit() + return jsonify({"task":chosen_task.return_body()}), 200 + # return check_complete_status(task_id, result = datetime.now()) +@task_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_incomplete_update(task_id): + chosen_task = validate_task(task_id) + task = Task.query.get(task_id) + if task is None: + return make_response("The task was not found", 404) + task.completed_at = None + db.session.commit() + return jsonify({"task":chosen_task.return_body()}), 200 - - \ No newline at end of file +# helper function to check the value of completed_at +# def check_complete_status(task_id, result): +# chosen_task = validate_task(task_id) +# task = Task.query.get(task_id) +# if task is None: +# return make_response("The task was not found", 404) +# task.complete_at = result +# db.session.commit() +# return jsonify({"task":chosen_task.return_body()}), 200 \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..f556ee3f3 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 """ @@ -25,7 +25,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_complete") - response_body = response.get_json() + response_body = response.get_json() # Assert assert response.status_code == 200 @@ -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,14 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert "message" in response_body + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +142,8 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert "message" in response_body + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From 4371548ebaf9f01be76869f6bfdb81868a15ea1a Mon Sep 17 00:00:00 2001 From: Miranda Date: Tue, 8 Nov 2022 21:49:38 -0800 Subject: [PATCH 07/14] Modify the /tasks//mark_complete route to make a call to the Slack API --- app/models/task.py | 1 - app/routes.py | 20 ++++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 200c12b62..9c991ad1b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -17,7 +17,6 @@ def return_body(self): "is_complete": self.check_complete_or_not() } - def check_complete_or_not(self): if self.completed_at: is_complete = True diff --git a/app/routes.py b/app/routes.py index c0aa4b544..d18f3e3b4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,7 +2,7 @@ from flask import Blueprint, request, make_response, jsonify, abort from app import db from app.models.task import Task -from sqlalchemy import asc, desc +import requests, os task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") @@ -112,15 +112,27 @@ def delete_one_task(task_id): @task_bp.route("//mark_complete", methods=["PATCH"]) def mark_complete_update(task_id): chosen_task = validate_task(task_id) - task = Task.query.get(task_id) if task is None: return make_response("The task was not found", 404) task.completed_at = datetime.now() - db.session.commit() + + PATH = "https://slack.com/api/chat.postMessage" + + SLACKBOT_TOKEN = os.environ.get("SLACKBOT_TOKEN") + + # the query parameters come from the + query_params = { + "token": SLACKBOT_TOKEN, + "channel": "task-notifications", + "text": f"Someone just completed the task {task.title}" + } + + requests.post(url=PATH, data=query_params, headers={"Authorization": SLACKBOT_TOKEN}) + # POST: to submit data to be processed to the server. + return jsonify({"task":chosen_task.return_body()}), 200 - # return check_complete_status(task_id, result = datetime.now()) @task_bp.route("//mark_incomplete", methods=["PATCH"]) From d482d77a5ae68f12c6c3d6e938e91c63d13dd119 Mon Sep 17 00:00:00 2001 From: Miranda Date: Wed, 9 Nov 2022 16:07:36 -0800 Subject: [PATCH 08/14] Added Goal model, created POST, GET, and GET by id routes for Goals --- app/__init__.py | 5 +- app/models/goal.py | 10 +++ app/models/task.py | 3 + app/routes.py | 78 +++++++++++++++++-- ...e_added_a_goal_model_with_id_and_title_.py | 28 +++++++ tests/test_wave_05.py | 68 +++++++++++----- 6 files changed, 166 insertions(+), 26 deletions(-) create mode 100644 migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py diff --git a/app/__init__.py b/app/__init__.py index f996a906b..21e4ce6d5 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,8 +30,11 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from app.routes import task_bp + from app.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..e34632195 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,13 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + # tasks = db.relationship("Task", back_populateds="goal") + # "goal" here is related to goal = db.relationship("Goal", back_populated="tasks") + + + def return_body(self): + return { + "id": self.goal_id, + "title": self.title + } \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 9c991ad1b..4cbf93204 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,7 +8,10 @@ class Task(db.Model): title = db.Column(db.String) description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) + # goal_title = db.Column(db.Integer, db.ForeignKey('goal.title')) + # goal = db.relationship("Goal", back_populated="tasks") + def return_body(self): return { "id": self.task_id, diff --git a/app/routes.py b/app/routes.py index d18f3e3b4..d1d2501d8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,9 +2,11 @@ from flask import Blueprint, request, make_response, jsonify, abort from app import db from app.models.task import Task +from app.models.goal import Goal import requests, os task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") +goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goals") # helper function def validate_task(task_id): @@ -22,6 +24,7 @@ def validate_task(task_id): return matching_task + # Create a Task: Valid Task With null completed_at @task_bp.route("", methods=["POST"]) def create_task(): @@ -67,7 +70,6 @@ def read_task(): else: tasks = Task.query.all() - response = [] response = [task.return_body() for task in tasks] return jsonify(response), 200 @@ -130,6 +132,7 @@ def mark_complete_update(task_id): } requests.post(url=PATH, data=query_params, headers={"Authorization": SLACKBOT_TOKEN}) + # using json=query_params connot connect to the slack # POST: to submit data to be processed to the server. return jsonify({"task":chosen_task.return_body()}), 200 @@ -147,11 +150,76 @@ def mark_incomplete_update(task_id): # helper function to check the value of completed_at -# def check_complete_status(task_id, result): -# chosen_task = validate_task(task_id) -# task = Task.query.get(task_id) +# def check_complete_status(goal_id, result): +# chosen_task = validate_task(goal_id) +# task = Task.query.get(goal_id) # if task is None: # return make_response("The task was not found", 404) # task.complete_at = result # db.session.commit() -# return jsonify({"task":chosen_task.return_body()}), 200 \ No newline at end of file +# return jsonify({"task":chosen_task.return_body()}), 200 + + + + +# =============================================================== +# Goal Routes + +def validate_goal(goal_id): + try: + goal_id = int(goal_id) + except ValueError: + response_str = f"Invalid task id: {goal_id} must be an integer" + abort(make_response(jsonify({"message":response_str}), 400)) + + matching_goal = Goal.query.get(goal_id) + + if not matching_goal: + abort(make_response(jsonify({"message": f"The {goal_id} is not found"}), 404)) + + return matching_goal + +@goal_bp.route("", methods=["POST"]) +def create_goal(): + response_body = request.get_json() + + if "title" not in response_body: + return jsonify({"details": "Invalid data"}), 400 + + new_goal = Goal( + title = response_body["title"] + ) + + db.session.add(new_goal) + db.session.commit() + return jsonify({"goal":new_goal.return_body()}), 201 + + +# Get Goals: Getting Saved Goals +@goal_bp.route("", methods=["GET"]) +def read_goal(): + goals = Goal.query.all() + response = [goal.return_body() for goal in goals] + return jsonify(response), 200 + + +#Get One Goal: One Saved Goal +@goal_bp.route("/", methods=["GET"]) +def get_one_goal_by_id(goal_id): + chosen_goal= validate_goal(goal_id) + return jsonify({"goal":chosen_goal.return_body()}), 200 + + +# Update Goal +@task_bp.route("/", methods=["PUT"]) +def update_task(task_id): + # after update the task, it becomes to the last one + # id order: 2341 + chosen_task = validate_task(task_id) + request_body = request.get_json() + + chosen_task.title = request_body["title"] + chosen_task.description = request_body["description"] + + db.session.commit() + return jsonify({"task":chosen_task.return_body()}), 200 \ No newline at end of file diff --git a/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py b/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py new file mode 100644 index 000000000..616358994 --- /dev/null +++ b/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py @@ -0,0 +1,28 @@ +"""Added a Goal model with id and title attributes + +Revision ID: f4e9bb4a99ae +Revises: 143607d7509b +Create Date: 2022-11-09 15:07:30.825612 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f4e9bb4a99ae' +down_revision = '143607d7509b' +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..075875861 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,8 @@ +from app.models.goal import Goal import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +13,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -29,7 +30,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +47,25 @@ 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 "message" in response_body # ---- 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 +84,54 @@ 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.post("/goals", json={ + "title": "Updata My New Goal" + }) + response_body = response.get_json() + # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here # assertion 2 goes here # assertion 3 goes here + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updata My New Goal" + } + } + goal = Goal.query.get(1) + assert goal.title == "Updata My New Goal" + # ---- Complete Assertions Here ---- + - -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- - + response = client.put("/goals/1", json={ + "title": "Updata My New Goal", + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here # assertion 2 goes here + assert response.status_code == 404 + assert "message" in response_body # ---- 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 +147,32 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 + assert "message" in response_body + # raise Exception("Complete test with assertion about response body") - raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@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 # assertion 2 goes here + assert response.status_code == 404 + assert "message" in response_body # ---- 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 98fb423be262c725da81776ab0f0d2693a86be6d Mon Sep 17 00:00:00 2001 From: Miranda Date: Wed, 9 Nov 2022 18:04:46 -0800 Subject: [PATCH 09/14] added update(PUT) and DELETE route to Goals --- app/routes.py | 25 ++++++++++++++++--------- tests/test_wave_05.py | 3 +-- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index d1d2501d8..54303d969 100644 --- a/app/routes.py +++ b/app/routes.py @@ -107,7 +107,6 @@ def delete_one_task(task_id): db.session.delete(task_to_delete) db.session.commit() - # mistakes in the return sentence trapped me for some time return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 @@ -179,6 +178,7 @@ def validate_goal(goal_id): return matching_goal + @goal_bp.route("", methods=["POST"]) def create_goal(): response_body = request.get_json() @@ -211,15 +211,22 @@ def get_one_goal_by_id(goal_id): # Update Goal -@task_bp.route("/", methods=["PUT"]) -def update_task(task_id): - # after update the task, it becomes to the last one - # id order: 2341 - chosen_task = validate_task(task_id) +@goal_bp.route("/", methods=["PUT"]) +def update_goal(goal_id): + chosen_goal = validate_goal(goal_id) request_body = request.get_json() - chosen_task.title = request_body["title"] - chosen_task.description = request_body["description"] + chosen_goal.title = request_body["title"] db.session.commit() - return jsonify({"task":chosen_task.return_body()}), 200 \ No newline at end of file + return jsonify({"goal":chosen_goal.return_body()}), 200 + + +@goal_bp.route("/", methods=["DELETE"]) +def delete_goal_by_id(goal_id): + chosen_goal = validate_goal(goal_id) + + db.session.delete(chosen_goal) + db.session.commit() + + return jsonify({"details": f'Goal {chosen_goal.goal_id} "{chosen_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 075875861..dcccdab39 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -89,7 +89,7 @@ def test_update_goal(client, one_goal): # raise Exception("Complete test") # Act # ---- Complete Act Here ---- - response = client.post("/goals", json={ + response = client.put("/goals/1", json={ "title": "Updata My New Goal" }) response_body = response.get_json() @@ -147,7 +147,6 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 - assert "message" in response_body # raise Exception("Complete test with assertion about response body") # ***************************************************************** From c945e3b6de52ad4fba404b593969557e210f33d1 Mon Sep 17 00:00:00 2001 From: Miranda Date: Wed, 9 Nov 2022 23:58:57 -0800 Subject: [PATCH 10/14] Added Procfile file --- Procfile | 1 + app/__init__.py | 6 +- app/models/goal.py | 17 ++- app/models/task.py | 32 ++--- app/routes.py | 114 +++++++----------- app/routes_helper.py | 16 +++ ...pdate_the_task_and_goal_model_to_build_.py | 30 +++++ migrations/versions/7af0cba0fdc8_debuging.py | 30 +++++ .../versions/fc02b7c260ee_added_task_model.py | 40 ++++++ tests/test_wave_01.py | 3 + tests/test_wave_05.py | 2 +- tests/test_wave_06.py | 16 +-- 12 files changed, 207 insertions(+), 100 deletions(-) create mode 100644 Procfile create mode 100644 app/routes_helper.py create mode 100644 migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py create mode 100644 migrations/versions/7af0cba0fdc8_debuging.py create mode 100644 migrations/versions/fc02b7c260ee_added_task_model.py 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/app/__init__.py b/app/__init__.py index 21e4ce6d5..85b9126d7 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,8 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate -import os from dotenv import load_dotenv +import os db = SQLAlchemy() @@ -30,11 +30,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from app.routes import task_bp, goal_bp + from app.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 e34632195..f0e52f516 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,12 +4,23 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) - # tasks = db.relationship("Task", back_populateds="goal") - # "goal" here is related to goal = db.relationship("Goal", back_populated="tasks") + + tasks = db.relationship("Task", back_populates="goal", lazy=True) + # Lazy parameter determines how the related objects get loaded + # when querying through relationships. def return_body(self): return { "id": self.goal_id, "title": self.title - } \ No newline at end of file + } + + + @classmethod + def from_dict(cls, data_dict): + if "title" in data_dict: + new_obj = cls(title=data_dict["title"]) + return new_obj + + diff --git a/app/models/task.py b/app/models/task.py index 4cbf93204..d66ebab13 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,10 +8,11 @@ class Task(db.Model): title = db.Column(db.String) description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) - # goal_title = db.Column(db.Integer, db.ForeignKey('goal.title')) - # goal = db.relationship("Goal", back_populated="tasks") - + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) + goal = db.relationship("Goal", back_populates="tasks") + + def return_body(self): return { "id": self.task_id, @@ -20,6 +21,20 @@ def return_body(self): "is_complete": self.check_complete_or_not() } + + @classmethod + def from_dict(cls, data_dict): + if "title" in data_dict and\ + "description" in data_dict and\ + "is_complete" in data_dict: + new_obj = cls( + title=data_dict["title"], + description=data_dict["description"], + completed_at=data_dict["is_complete"] + ) + return new_obj + + def check_complete_or_not(self): if self.completed_at: is_complete = True @@ -28,14 +43,3 @@ def check_complete_or_not(self): return is_complete - # @classmethod - # def from_dict(cls, data_dict): - # # cls represents all the class variables - # if "title" in data_dict and "description" in data_dict and\ - # "is_complete" in data_dict: - # new_obj = cls( - # title=data_dict["title"], - # description=data_dict["description"], - # completed_at=data_dict["is_complete"] - # ) - # return new_obj diff --git a/app/routes.py b/app/routes.py index 54303d969..2d079e113 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,28 +1,14 @@ +import requests, os from datetime import datetime -from flask import Blueprint, request, make_response, jsonify, abort +from flask import Blueprint, request, make_response, jsonify from app import db from app.models.task import Task from app.models.goal import Goal -import requests, os - -task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") -goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goals") - -# helper function -def validate_task(task_id): - try: - task_id = int(task_id) - except ValueError: - response_str = f"Invalid task id: {task_id} must be an integer" - abort(make_response(jsonify({"message":response_str}), 400)) - - matching_task = Task.query.get(task_id) - - if not matching_task: - abort(make_response(jsonify({"message": f"The {task_id} is not found"}), 404)) +from app.routes_helper import get_one_obj_or_abort - return matching_task +task_bp = Blueprint("task_bp", __name__, url_prefix="/task") +goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goal") # Create a Task: Valid Task With null completed_at @@ -30,19 +16,12 @@ def validate_task(task_id): def create_task(): response_body = request.get_json() - # If add "is_complete" not in respnse_body - # in postman it return 500. - # Haven't solve the problem, so I take out that line if "title" not in response_body or\ - "description" not in response_body: - # "is_complete" not in respnse_body + "description" not in response_body or\ + "is_complete" not in response_body: return jsonify({"details": "Invalid data"}), 400 - new_task = Task( - title = response_body["title"], - description = response_body["description"], - # completed_at = response_body["is_complete"] - ) + new_task = Task.from_dict(response_body) db.session.add(new_task) db.session.commit() @@ -54,13 +33,6 @@ def create_task(): # Get Tasks: Getting Saved Tasks, sorting by ascending/descending @task_bp.route("", methods=["GET"]) def read_task(): - # tasks = Task.query.all() - - # read_task_result = [] - # # for task in tasks: - # # read_task_result.append(task.return_body()) - # read_task_result = [task.return_body() for task in tasks] - # return jsonify(read_task_result), 200 sort_query = request.args.get("sort") if sort_query == "asc": @@ -78,7 +50,7 @@ def read_task(): # Get One Task: One Saved Task @task_bp.route("/", methods=["GET"]) def get_one_task_by_id(task_id): - chosen_task = validate_task(task_id) + chosen_task = get_one_obj_or_abort(Task, task_id) return jsonify({"task":chosen_task.return_body()}), 200 @@ -86,11 +58,8 @@ def get_one_task_by_id(task_id): # Update Task @task_bp.route("/", methods=["PUT"]) def update_task(task_id): - # after update the task, it becomes to the last one - # id order: 2341 - chosen_task = validate_task(task_id) + chosen_task = get_one_obj_or_abort(Task, task_id) request_body = request.get_json() - chosen_task.title = request_body["title"] chosen_task.description = request_body["description"] @@ -102,17 +71,17 @@ def update_task(task_id): # Deleting a Task @task_bp.route("/", methods=["DELETE"]) def delete_one_task(task_id): - task_to_delete = validate_task(task_id) + task_to_delete = get_one_obj_or_abort(Task, task_id) db.session.delete(task_to_delete) db.session.commit() return jsonify({"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}), 200 - + @task_bp.route("//mark_complete", methods=["PATCH"]) def mark_complete_update(task_id): - chosen_task = validate_task(task_id) + chosen_task = get_one_obj_or_abort(Task, task_id) task = Task.query.get(task_id) if task is None: return make_response("The task was not found", 404) @@ -131,7 +100,6 @@ def mark_complete_update(task_id): } requests.post(url=PATH, data=query_params, headers={"Authorization": SLACKBOT_TOKEN}) - # using json=query_params connot connect to the slack # POST: to submit data to be processed to the server. return jsonify({"task":chosen_task.return_body()}), 200 @@ -139,7 +107,7 @@ def mark_complete_update(task_id): @task_bp.route("//mark_incomplete", methods=["PATCH"]) def mark_incomplete_update(task_id): - chosen_task = validate_task(task_id) + chosen_task = get_one_obj_or_abort(Task, task_id) task = Task.query.get(task_id) if task is None: return make_response("The task was not found", 404) @@ -149,7 +117,7 @@ def mark_incomplete_update(task_id): # helper function to check the value of completed_at -# def check_complete_status(goal_id, result): +# def check_task_status(goal_id, result): # chosen_task = validate_task(goal_id) # task = Task.query.get(goal_id) # if task is None: @@ -161,24 +129,8 @@ def mark_incomplete_update(task_id): -# =============================================================== -# Goal Routes - -def validate_goal(goal_id): - try: - goal_id = int(goal_id) - except ValueError: - response_str = f"Invalid task id: {goal_id} must be an integer" - abort(make_response(jsonify({"message":response_str}), 400)) - - matching_goal = Goal.query.get(goal_id) - - if not matching_goal: - abort(make_response(jsonify({"message": f"The {goal_id} is not found"}), 404)) - - return matching_goal - +# create goal @goal_bp.route("", methods=["POST"]) def create_goal(): response_body = request.get_json() @@ -195,7 +147,7 @@ def create_goal(): return jsonify({"goal":new_goal.return_body()}), 201 -# Get Goals: Getting Saved Goals +# Get Goals @goal_bp.route("", methods=["GET"]) def read_goal(): goals = Goal.query.all() @@ -203,17 +155,17 @@ def read_goal(): return jsonify(response), 200 -#Get One Goal: One Saved Goal +# Get One Goal @goal_bp.route("/", methods=["GET"]) def get_one_goal_by_id(goal_id): - chosen_goal= validate_goal(goal_id) + chosen_goal= get_one_obj_or_abort(Goal, goal_id) return jsonify({"goal":chosen_goal.return_body()}), 200 # Update Goal @goal_bp.route("/", methods=["PUT"]) def update_goal(goal_id): - chosen_goal = validate_goal(goal_id) + chosen_goal = get_one_obj_or_abort(Goal, goal_id) request_body = request.get_json() chosen_goal.title = request_body["title"] @@ -222,11 +174,33 @@ def update_goal(goal_id): return jsonify({"goal":chosen_goal.return_body()}), 200 +# Delete Goal @goal_bp.route("/", methods=["DELETE"]) def delete_goal_by_id(goal_id): - chosen_goal = validate_goal(goal_id) + chosen_goal = get_one_obj_or_abort(Goal, goal_id) db.session.delete(chosen_goal) db.session.commit() - return jsonify({"details": f'Goal {chosen_goal.goal_id} "{chosen_goal.title}" successfully deleted'}), 200 \ No newline at end of file + return jsonify({"details": f'Goal {chosen_goal.goal_id} "{chosen_goal.title}" successfully deleted'}), 200 + + + + +# ================================================== +# One-to-Many Relationship bewteen goals and tasks +# ================================================== + +# @goal_bp.route("//task", methods=["POST"]) +# def post_task_belonging_to_a_goal(goal_id): +# parent_goal = get_one_obj_or_abort(Goal, goal_id) + +# request_body = request.get_json() + +# new_task = Task.from_dict(request_body) +# new_task.goal = parent_goal + +# db.session.add(new_task) +# db.session.commit() + +# return jsonify({f"id": {new_task.goal.goal_id}, "task_ids": {new_task.task_id}}), 201 \ No newline at end of file diff --git a/app/routes_helper.py b/app/routes_helper.py new file mode 100644 index 000000000..503785eb8 --- /dev/null +++ b/app/routes_helper.py @@ -0,0 +1,16 @@ +from flask import jsonify, abort, make_response + +def get_one_obj_or_abort(cls, obj_id): + try: + obj_id = int(obj_id) + except ValueError: + response_str = f"Invalid Bike ID: '{obj_id}' must be an integer" + abort(make_response(jsonify({"message":response_str}), 400)) + + matching_obj = cls.query.get(obj_id) + + if not matching_obj: + response_str = f"Bike ID: '{cls.__name__}' was not found in the database" + abort(make_response(jsonify({"message":response_str}), 404)) + + return matching_obj \ No newline at end of file diff --git a/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py b/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py new file mode 100644 index 000000000..1545c6923 --- /dev/null +++ b/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py @@ -0,0 +1,30 @@ +"""update the Task and Goal model to build the connection + +Revision ID: 13fab4342ca9 +Revises: f4e9bb4a99ae +Create Date: 2022-11-09 19:35:15.196274 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '13fab4342ca9' +down_revision = 'f4e9bb4a99ae' +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 ### diff --git a/migrations/versions/7af0cba0fdc8_debuging.py b/migrations/versions/7af0cba0fdc8_debuging.py new file mode 100644 index 000000000..2257ca207 --- /dev/null +++ b/migrations/versions/7af0cba0fdc8_debuging.py @@ -0,0 +1,30 @@ +"""debuging + +Revision ID: 7af0cba0fdc8 +Revises: 13fab4342ca9 +Create Date: 2022-11-09 21:34:13.523112 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7af0cba0fdc8' +down_revision = '13fab4342ca9' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint('task_goal_id_fkey', 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('goal_id', sa.INTEGER(), autoincrement=False, nullable=True)) + op.create_foreign_key('task_goal_id_fkey', 'task', 'goal', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### diff --git a/migrations/versions/fc02b7c260ee_added_task_model.py b/migrations/versions/fc02b7c260ee_added_task_model.py new file mode 100644 index 000000000..4d3aa85ff --- /dev/null +++ b/migrations/versions/fc02b7c260ee_added_task_model.py @@ -0,0 +1,40 @@ +"""added task model + +Revision ID: fc02b7c260ee +Revises: 7af0cba0fdc8 +Create Date: 2022-11-09 23:12:55.701305 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fc02b7c260ee' +down_revision = '7af0cba0fdc8' +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.Column('title', sa.String(), nullable=True), + 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.String(), 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/tests/test_wave_01.py b/tests/test_wave_01.py index a0114b785..45e5e06f7 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -73,6 +73,7 @@ def test_create_task(client): response = client.post("/tasks", json={ "title": "A Brand New Task", "description": "Test Description", + "is_complete": None }) response_body = response.get_json() @@ -100,6 +101,8 @@ def test_update_task(client, one_task): response = client.put("/tasks/1", json={ "title": "Updated Task Title", "description": "Updated Test Description", + "is_complete": None + }) response_body = response.get_json() diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index dcccdab39..8297b2643 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -148,7 +148,7 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 # raise Exception("Complete test with assertion about response body") - + assert "details" in response_body # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..041eb3b4a 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 "message" in response_body + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_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 2254dd65a9f340eab4ea2ec3894d8172f7bb8586 Mon Sep 17 00:00:00 2001 From: Miranda Date: Thu, 10 Nov 2022 11:08:54 -0800 Subject: [PATCH 11/14] after debugging, past wave 1-5 tests --- app/models/goal.py | 7 ++-- app/models/task.py | 11 +++--- app/routes.py | 28 +++++++------ ...pdate_the_task_and_goal_model_to_build_.py | 30 -------------- migrations/versions/143607d7509b_.py | 38 ------------------ migrations/versions/50e6ba6b2899_.py | 39 ------------------- migrations/versions/7af0cba0fdc8_debuging.py | 30 -------------- ...ad251048a8_added_migrations_file_again.py} | 18 +++++---- ...e_added_a_goal_model_with_id_and_title_.py | 28 ------------- tests/test_wave_01.py | 2 +- tests/test_wave_03.py | 1 - 11 files changed, 32 insertions(+), 200 deletions(-) delete mode 100644 migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py delete mode 100644 migrations/versions/143607d7509b_.py delete mode 100644 migrations/versions/50e6ba6b2899_.py delete mode 100644 migrations/versions/7af0cba0fdc8_debuging.py rename migrations/versions/{fc02b7c260ee_added_task_model.py => ecad251048a8_added_migrations_file_again.py} (65%) delete mode 100644 migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py diff --git a/app/models/goal.py b/app/models/goal.py index f0e52f516..942775e44 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,13 +1,12 @@ from app import db + class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + goal_id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String) - tasks = db.relationship("Task", back_populates="goal", lazy=True) - # Lazy parameter determines how the related objects get loaded - # when querying through relationships. + def return_body(self): diff --git a/app/models/task.py b/app/models/task.py index d66ebab13..ded2b2935 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -4,15 +4,14 @@ # create the table with attributes # after created, flask db migrate, flask db upgrade 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.String) completed_at = db.Column(db.DateTime, nullable=True) - - goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'),nullable=True) goal = db.relationship("Goal", back_populates="tasks") - + def return_body(self): return { "id": self.task_id, @@ -26,11 +25,11 @@ def return_body(self): def from_dict(cls, data_dict): if "title" in data_dict and\ "description" in data_dict and\ - "is_complete" in data_dict: + "completed_at" in data_dict: new_obj = cls( title=data_dict["title"], description=data_dict["description"], - completed_at=data_dict["is_complete"] + completed_at=data_dict["completed_at"] ) return new_obj diff --git a/app/routes.py b/app/routes.py index 2d079e113..7cbd70196 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,8 +7,8 @@ from app.routes_helper import get_one_obj_or_abort -task_bp = Blueprint("task_bp", __name__, url_prefix="/task") -goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goal") +task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks") +goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goals") # Create a Task: Valid Task With null completed_at @@ -18,7 +18,7 @@ def create_task(): if "title" not in response_body or\ "description" not in response_body or\ - "is_complete" not in response_body: + "completed_at" not in response_body: return jsonify({"details": "Invalid data"}), 400 new_task = Task.from_dict(response_body) @@ -138,9 +138,7 @@ def create_goal(): if "title" not in response_body: return jsonify({"details": "Invalid data"}), 400 - new_goal = Goal( - title = response_body["title"] - ) + new_goal = Goal(title = response_body["title"]) db.session.add(new_goal) db.session.commit() @@ -191,16 +189,16 @@ def delete_goal_by_id(goal_id): # One-to-Many Relationship bewteen goals and tasks # ================================================== -# @goal_bp.route("//task", methods=["POST"]) -# def post_task_belonging_to_a_goal(goal_id): -# parent_goal = get_one_obj_or_abort(Goal, goal_id) +@goal_bp.route("//tasks", methods=["POST"]) +def post_task_belonging_to_a_goal(goal_id): + parent_goal = get_one_obj_or_abort(Goal, goal_id) -# request_body = request.get_json() + request_body = request.get_json() -# new_task = Task.from_dict(request_body) -# new_task.goal = parent_goal + new_task = Task.from_dict(request_body) + new_task.goal = parent_goal -# db.session.add(new_task) -# db.session.commit() + db.session.add(new_task) + db.session.commit() -# return jsonify({f"id": {new_task.goal.goal_id}, "task_ids": {new_task.task_id}}), 201 \ No newline at end of file + return jsonify({f"id": {new_task.goal.goal_id}, "task_ids": {new_task.task_id}}), 201 \ No newline at end of file diff --git a/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py b/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py deleted file mode 100644 index 1545c6923..000000000 --- a/migrations/versions/13fab4342ca9_update_the_task_and_goal_model_to_build_.py +++ /dev/null @@ -1,30 +0,0 @@ -"""update the Task and Goal model to build the connection - -Revision ID: 13fab4342ca9 -Revises: f4e9bb4a99ae -Create Date: 2022-11-09 19:35:15.196274 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '13fab4342ca9' -down_revision = 'f4e9bb4a99ae' -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 ### diff --git a/migrations/versions/143607d7509b_.py b/migrations/versions/143607d7509b_.py deleted file mode 100644 index 28784e845..000000000 --- a/migrations/versions/143607d7509b_.py +++ /dev/null @@ -1,38 +0,0 @@ -"""empty message - -Revision ID: 143607d7509b -Revises: 50e6ba6b2899 -Create Date: 2022-11-02 14:09:36.795693 - -""" -from alembic import op -import sqlalchemy as sa -from sqlalchemy.dialects import postgresql - -# revision identifiers, used by Alembic. -revision = '143607d7509b' -down_revision = '50e6ba6b2899' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('completed_at', sa.DateTime(), nullable=True)) - op.add_column('task', sa.Column('description', sa.String(), nullable=True)) - op.add_column('task', sa.Column('title', sa.String(), nullable=True)) - op.drop_column('task', 'task_description') - op.drop_column('task', 'task_title') - op.drop_column('task', 'task_completed_at') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('task_completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) - op.add_column('task', sa.Column('task_title', sa.VARCHAR(), autoincrement=False, nullable=True)) - op.add_column('task', sa.Column('task_description', sa.VARCHAR(), autoincrement=False, nullable=True)) - op.drop_column('task', 'title') - op.drop_column('task', 'description') - op.drop_column('task', 'completed_at') - # ### end Alembic commands ### diff --git a/migrations/versions/50e6ba6b2899_.py b/migrations/versions/50e6ba6b2899_.py deleted file mode 100644 index c095259d9..000000000 --- a/migrations/versions/50e6ba6b2899_.py +++ /dev/null @@ -1,39 +0,0 @@ -"""empty message - -Revision ID: 50e6ba6b2899 -Revises: -Create Date: 2022-11-02 14:07:23.594711 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '50e6ba6b2899' -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('task_title', sa.String(), nullable=True), - sa.Column('task_description', sa.String(), nullable=True), - sa.Column('task_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/7af0cba0fdc8_debuging.py b/migrations/versions/7af0cba0fdc8_debuging.py deleted file mode 100644 index 2257ca207..000000000 --- a/migrations/versions/7af0cba0fdc8_debuging.py +++ /dev/null @@ -1,30 +0,0 @@ -"""debuging - -Revision ID: 7af0cba0fdc8 -Revises: 13fab4342ca9 -Create Date: 2022-11-09 21:34:13.523112 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '7af0cba0fdc8' -down_revision = '13fab4342ca9' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_constraint('task_goal_id_fkey', 'task', type_='foreignkey') - op.drop_column('task', 'goal_id') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('goal_id', sa.INTEGER(), autoincrement=False, nullable=True)) - op.create_foreign_key('task_goal_id_fkey', 'task', 'goal', ['goal_id'], ['goal_id']) - # ### end Alembic commands ### diff --git a/migrations/versions/fc02b7c260ee_added_task_model.py b/migrations/versions/ecad251048a8_added_migrations_file_again.py similarity index 65% rename from migrations/versions/fc02b7c260ee_added_task_model.py rename to migrations/versions/ecad251048a8_added_migrations_file_again.py index 4d3aa85ff..4c4fc0cec 100644 --- a/migrations/versions/fc02b7c260ee_added_task_model.py +++ b/migrations/versions/ecad251048a8_added_migrations_file_again.py @@ -1,8 +1,8 @@ -"""added task model +"""added migrations file again -Revision ID: fc02b7c260ee -Revises: 7af0cba0fdc8 -Create Date: 2022-11-09 23:12:55.701305 +Revision ID: ecad251048a8 +Revises: +Create Date: 2022-11-10 09:28:23.151577 """ from alembic import op @@ -10,8 +10,8 @@ # revision identifiers, used by Alembic. -revision = 'fc02b7c260ee' -down_revision = '7af0cba0fdc8' +revision = 'ecad251048a8' +down_revision = None branch_labels = None depends_on = None @@ -19,15 +19,17 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('goal', - sa.Column('goal_id', sa.Integer(), nullable=False), + sa.Column('goal_id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('title', sa.String(), nullable=True), sa.PrimaryKeyConstraint('goal_id') ) op.create_table('task', - sa.Column('task_id', sa.Integer(), nullable=False), + 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('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.goal_id'], ), sa.PrimaryKeyConstraint('task_id') ) # ### end Alembic commands ### diff --git a/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py b/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py deleted file mode 100644 index 616358994..000000000 --- a/migrations/versions/f4e9bb4a99ae_added_a_goal_model_with_id_and_title_.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Added a Goal model with id and title attributes - -Revision ID: f4e9bb4a99ae -Revises: 143607d7509b -Create Date: 2022-11-09 15:07:30.825612 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'f4e9bb4a99ae' -down_revision = '143607d7509b' -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_01.py b/tests/test_wave_01.py index 45e5e06f7..9fafabcd9 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -73,7 +73,7 @@ def test_create_task(client): response = client.post("/tasks", json={ "title": "A Brand New Task", "description": "Test Description", - "is_complete": None + "completed_at": None }) response_body = response.get_json() diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index f556ee3f3..b243b1d3d 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -1,4 +1,3 @@ -import unittest from unittest.mock import Mock, patch from datetime import datetime from app.models.task import Task From 2b515b48ba6a42b67d7a01064ffed481eee56fde Mon Sep 17 00:00:00 2001 From: Miranda Date: Fri, 11 Nov 2022 12:59:08 -0800 Subject: [PATCH 12/14] added POST route to Sending a List of Task IDs to a Goal and a GET route to Getting Tasks of One Goal --- app/__init__.py | 4 +- app/goal.py | 97 +++++++++++++++++++++++++++++++++++++ app/models/goal.py | 4 +- app/models/task.py | 8 ++- app/routes_helper.py | 4 +- app/{routes.py => tasks.py} | 73 ---------------------------- tests/test_wave_01.py | 1 + tests/test_wave_03.py | 2 +- 8 files changed, 111 insertions(+), 82 deletions(-) create mode 100644 app/goal.py rename app/{routes.py => tasks.py} (66%) diff --git a/app/__init__.py b/app/__init__.py index 85b9126d7..4d8a2875d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,7 +30,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from app.routes import task_bp, goal_bp + from app.tasks import task_bp + from app.goal import goal_bp + app.register_blueprint(task_bp) app.register_blueprint(goal_bp) diff --git a/app/goal.py b/app/goal.py new file mode 100644 index 000000000..07429365d --- /dev/null +++ b/app/goal.py @@ -0,0 +1,97 @@ + +from flask import Blueprint, request, make_response, jsonify +from app import db +from app.models.task import Task +from app.models.goal import Goal +from app.routes_helper import get_one_obj_or_abort + +goal_bp = Blueprint("goal_bp", __name__, url_prefix="/goals") + + +# create goal +@goal_bp.route("", methods=["POST"]) +def create_goal(): + response_body = request.get_json() + + if "title" not in response_body: + return jsonify({"details": "Invalid data"}), 400 + + new_goal = Goal(title = response_body["title"]) + + db.session.add(new_goal) + db.session.commit() + return jsonify({"goal":new_goal.return_body()}), 201 + + +# Get Goals +@goal_bp.route("", methods=["GET"]) +def read_goal(): + goals = Goal.query.all() + response = [goal.return_body() for goal in goals] + return jsonify(response), 200 + + +# Get One Goal +@goal_bp.route("/", methods=["GET"]) +def get_one_goal_by_id(goal_id): + chosen_goal= get_one_obj_or_abort(Goal, goal_id) + return jsonify({"goal":chosen_goal.return_body()}), 200 + + +# Update Goal +@goal_bp.route("/", methods=["PUT"]) +def update_goal(goal_id): + chosen_goal = get_one_obj_or_abort(Goal, goal_id) + request_body = request.get_json() + + chosen_goal.title = request_body["title"] + + db.session.commit() + return jsonify({"goal":chosen_goal.return_body()}), 200 + + +# Delete Goal +@goal_bp.route("/", methods=["DELETE"]) +def delete_goal_by_id(goal_id): + chosen_goal = get_one_obj_or_abort(Goal, goal_id) + + db.session.delete(chosen_goal) + db.session.commit() + + return jsonify({"details": f'Goal {chosen_goal.goal_id} "{chosen_goal.title}" successfully deleted'}), 200 + + + + +# ================================================== +# One-to-Many Relationship bewteen goals and tasks +# ================================================== + +@goal_bp.route("//tasks", methods=["POST"]) +def post_task_belonging_to_a_goal(goal_id): + parent_goal = get_one_obj_or_abort(Goal, goal_id) + request_body = request.get_json() + + for task in request_body["task_ids"]: + chosen_task = get_one_obj_or_abort(Task, task) + chosen_task.goal = parent_goal + + db.session.add(chosen_task) + db.session.commit() + + return jsonify({"id": int(goal_id), "task_ids": request_body["task_ids"]}), 200 + + + +@goal_bp.route("//tasks", methods=["GET"]) +def get_task_belonging_to_a_goal(goal_id): + parent_goal = get_one_obj_or_abort(Goal, goal_id) + + task_list = [] + for task in parent_goal.tasks: + task_list.append(task.return_body()) + + response_dict = parent_goal.return_body() + response_dict["tasks"] = task_list + return jsonify(response_dict), 200 + diff --git a/app/models/goal.py b/app/models/goal.py index 942775e44..2f11d66f0 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,19 +3,17 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) tasks = db.relationship("Task", back_populates="goal", lazy=True) - def return_body(self): return { "id": self.goal_id, "title": self.title } - @classmethod def from_dict(cls, data_dict): if "title" in data_dict: diff --git a/app/models/task.py b/app/models/task.py index ded2b2935..ff26a12fb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -4,7 +4,7 @@ # create the table with attributes # after created, flask db migrate, flask db upgrade class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + task_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) @@ -13,12 +13,16 @@ class Task(db.Model): def return_body(self): - return { + task_dict = { "id": self.task_id, "title": self.title, "description": self.description, "is_complete": self.check_complete_or_not() } + if self.goal_id: + task_dict["goal_id"] = self.goal_id + + return task_dict @classmethod diff --git a/app/routes_helper.py b/app/routes_helper.py index 503785eb8..b973ce721 100644 --- a/app/routes_helper.py +++ b/app/routes_helper.py @@ -4,13 +4,13 @@ def get_one_obj_or_abort(cls, obj_id): try: obj_id = int(obj_id) except ValueError: - response_str = f"Invalid Bike ID: '{obj_id}' must be an integer" + response_str = f"Invalid ID: '{obj_id}' must be an integer" abort(make_response(jsonify({"message":response_str}), 400)) matching_obj = cls.query.get(obj_id) if not matching_obj: - response_str = f"Bike ID: '{cls.__name__}' was not found in the database" + response_str = f"ID: '{cls.__name__}' was not found in the database" abort(make_response(jsonify({"message":response_str}), 404)) return matching_obj \ No newline at end of file diff --git a/app/routes.py b/app/tasks.py similarity index 66% rename from app/routes.py rename to app/tasks.py index 7cbd70196..b8cff68c2 100644 --- a/app/routes.py +++ b/app/tasks.py @@ -3,7 +3,6 @@ from flask import Blueprint, request, make_response, jsonify from app import db from app.models.task import Task -from app.models.goal import Goal from app.routes_helper import get_one_obj_or_abort @@ -130,75 +129,3 @@ def mark_incomplete_update(task_id): -# create goal -@goal_bp.route("", methods=["POST"]) -def create_goal(): - response_body = request.get_json() - - if "title" not in response_body: - return jsonify({"details": "Invalid data"}), 400 - - new_goal = Goal(title = response_body["title"]) - - db.session.add(new_goal) - db.session.commit() - return jsonify({"goal":new_goal.return_body()}), 201 - - -# Get Goals -@goal_bp.route("", methods=["GET"]) -def read_goal(): - goals = Goal.query.all() - response = [goal.return_body() for goal in goals] - return jsonify(response), 200 - - -# Get One Goal -@goal_bp.route("/", methods=["GET"]) -def get_one_goal_by_id(goal_id): - chosen_goal= get_one_obj_or_abort(Goal, goal_id) - return jsonify({"goal":chosen_goal.return_body()}), 200 - - -# Update Goal -@goal_bp.route("/", methods=["PUT"]) -def update_goal(goal_id): - chosen_goal = get_one_obj_or_abort(Goal, goal_id) - request_body = request.get_json() - - chosen_goal.title = request_body["title"] - - db.session.commit() - return jsonify({"goal":chosen_goal.return_body()}), 200 - - -# Delete Goal -@goal_bp.route("/", methods=["DELETE"]) -def delete_goal_by_id(goal_id): - chosen_goal = get_one_obj_or_abort(Goal, goal_id) - - db.session.delete(chosen_goal) - db.session.commit() - - return jsonify({"details": f'Goal {chosen_goal.goal_id} "{chosen_goal.title}" successfully deleted'}), 200 - - - - -# ================================================== -# One-to-Many Relationship bewteen goals and tasks -# ================================================== - -@goal_bp.route("//tasks", methods=["POST"]) -def post_task_belonging_to_a_goal(goal_id): - parent_goal = get_one_obj_or_abort(Goal, goal_id) - - request_body = request.get_json() - - new_task = Task.from_dict(request_body) - new_task.goal = parent_goal - - db.session.add(new_task) - db.session.commit() - - return jsonify({f"id": {new_task.goal.goal_id}, "task_ids": {new_task.task_id}}), 201 \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 9fafabcd9..95449ff26 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -1,3 +1,4 @@ + from app.models.task import Task import pytest diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index b243b1d3d..1557fa949 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -81,7 +81,7 @@ def test_mark_complete_on_completed_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_complete") - response_body = response.get_json() + response_body = response.get_json() # Assert assert response.status_code == 200 From 2dc97b3c1830b9954ce27e1b8e2e8c597de18a1e Mon Sep 17 00:00:00 2001 From: Miranda Date: Fri, 11 Nov 2022 13:13:58 -0800 Subject: [PATCH 13/14] delete Profile try to reconnect with heroku --- Procfile | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Procfile diff --git a/Procfile b/Procfile deleted file mode 100644 index 62e430aca..000000000 --- a/Procfile +++ /dev/null @@ -1 +0,0 @@ -web: gunicorn 'app:create_app()' \ No newline at end of file From 31410f6bace178db16c4eef22d3a7b7d63a9e449 Mon Sep 17 00:00:00 2001 From: Miranda Date: Fri, 11 Nov 2022 13:14:58 -0800 Subject: [PATCH 14/14] Added Procfile --- Procfile | 1 + 1 file changed, 1 insertion(+) 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