From 2ba7bbee84c558c4589ed1aba79065f6f3a87226 Mon Sep 17 00:00:00 2001 From: Ngozi Amaefule Date: Tue, 2 Nov 2021 22:44:54 -0400 Subject: [PATCH 1/4] Adedd POST and GET for all task and started GET for singular task --- app/__init__.py | 3 +- app/models/task.py | 8 ++- app/routes.py | 68 +++++++++++++++++++- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++++++ migrations/env.py | 96 ++++++++++++++++++++++++++++ migrations/script.py.mako | 24 +++++++ migrations/versions/001991e91f43_.py | 39 +++++++++++ 8 files changed, 280 insertions(+), 4 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/001991e91f43_.py diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..203d87760 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,6 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - + from app.routes import tasks_bp + app.register_blueprint(tasks_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..e04ef8404 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,10 @@ from flask import current_app from app import db - +# This the table class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + # These are the columns + 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) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..fa074863d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,68 @@ -from flask import Blueprint +from flask import Blueprint, jsonify, request +from flask.helpers import make_response +from app.models.task import Task +import datetime # datetime is a Python package so no need for "from datetime" +from app import db # Why from app and not app.__init___? +tasks_bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") + +@tasks_bp.route("", methods=["POST"]) +def create_tasks(): + request_body = request.get_json() + + if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body: + return jsonify({"details": "Invalid data"}), 400 + + new_task = Task( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"] + ) + + # SQLAlachemy has a class named session. Inside that class there is an instane method call add. + # This is telling SQLAlachemy to add new_task to the database. Think of add as a staging process + + db.session.add(new_task) + db.session.commit() + + response_body = { + "task": { + "id": new_task.task_id, + "title": new_task.title, + "description": new_task.description, + "is_complete": new_task.completed_at is not None + } + } + + return jsonify(response_body), 201 + +@tasks_bp.route("", methods=["GET"]) +def read_tasks(): + title_query = request.args.get("sort") + # Is "sort" a keyword? Can you replace it with "low" or "high"? Why not pass in "title"? + # Queries are the records (i.e. rows) + if title_query == "asc": + tasks = Task.query.order_by(Task.title.asc()) + elif title_query == "desc": + tasks = Task.query.order_by(Task.title.desc()) + else: + tasks = Task.query.all() + # Because Task is referring to a table, we are capturing all the records (rows) in the table and holding it in tasks. + + task_responses = [] + for task in tasks: + task_responses.append({ + { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at is not None + } + }) + + return jsonify(task_responses), 200 + +@tasks_bp.route("/", methods=["GET"]) +def read_task(task_id): + task_id = int(task_id) + task = Task.query.get(task_id) \ No newline at end of file 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"} diff --git a/migrations/versions/001991e91f43_.py b/migrations/versions/001991e91f43_.py new file mode 100644 index 000000000..e310c6bbb --- /dev/null +++ b/migrations/versions/001991e91f43_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 001991e91f43 +Revises: +Create Date: 2021-10-31 11:05:12.106716 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '001991e91f43' +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('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 b2c0abcedc7f0d9ea59dc9b2368c0b0fc6b82f65 Mon Sep 17 00:00:00 2001 From: Ngozi Amaefule Date: Wed, 3 Nov 2021 22:02:16 -0400 Subject: [PATCH 2/4] Added GET, POST, DELETE, PUT, and PATCH methods --- app/routes.py | 146 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 142 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index fa074863d..b2f43b154 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,8 +1,11 @@ from flask import Blueprint, jsonify, request from flask.helpers import make_response from app.models.task import Task -import datetime # datetime is a Python package so no need for "from datetime" +import requests +from datetime import datetime # datetime is a Python package so no need for "from datetime" from app import db # Why from app and not app.__init___? +import os +from dotenv import load_dotenv tasks_bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @@ -51,18 +54,153 @@ def read_tasks(): task_responses = [] for task in tasks: - task_responses.append({ + task_responses.append( { "id": task.task_id, "title": task.title, "description": task.description, "is_complete": task.completed_at is not None } - }) + ) return jsonify(task_responses), 200 @tasks_bp.route("/", methods=["GET"]) def read_task(task_id): task_id = int(task_id) - task = Task.query.get(task_id) \ No newline at end of file + task = Task.query.get(task_id) + + task_dict = {} + if task == None: + return jsonify(None), 404 + else: + task_dict = { + "task": { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at is not None + } + } + + return jsonify(task_dict), 200 + +@tasks_bp.route("/",methods=["PUT"]) +def update_task(task_id): + task_id = int(task_id) + task = Task.query.get(task_id) + + updated_body = request.get_json() + + if task == None: + return jsonify(None), 404 + + else: + task.title = updated_body["title"] + task.description = updated_body["description"] + + db.session.commit() + + task_dict = {} + task_dict = { + "task": { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at is not None + } + } + + return jsonify(task_dict), 200 + +@tasks_bp.route("/", methods=["DELETE"]) +def delete_task(task_id): + task_id = int(task_id) + task = Task.query.get(task_id) + + # deleted_body = request.get_json() + + if task == None: + return jsonify(None), 404 + + else: + db.session.delete(task) + db.session.commit() + + response_body = {} + response_body = { + "details": f'Task {task.task_id} "{task.title}" successfully deleted'} + return jsonify(response_body), 200 + +def slack_bot(title): + query_path = {'channel':'slack_api_test_channel', 'text': title} + header = {'Authorization': os.environ.get('BOT')} + response = requests.post('https://slack.com/api/chat.postMessage', params = query_path, headers = header) + return response.json() + +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +def update_complete(task_id): + task_id = int(task_id) + task = Task.query.get(task_id) + + if task == None: + return jsonify(None), 404 + + task.completed_at = datetime.now() + db.session.commit() + + slack_bot(task.title) + + # updated_body = request.get_json() + + + # if "title" in updated_body: + # task.title = updated_body["title"] + # elif "description" in updated_body: + # task.description = updated_body["description"] + # elif "completed_at" in updated_body: + # task.completed_at = updated_body["completed_at"] + + # db.session.commit() + # Isn't task updated with the correct/updated title, description, and completed_at at this point? + task_dict = {} + task_dict = { + "task": { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at is not None + } + } + + return jsonify(task_dict), 200 + +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def update_incomplete(task_id): + task_id = int(task_id) + task = Task.query.get(task_id) + + if task == None: + return jsonify(None), 404 + task.completed_at = None + + db.session.commit() + # updated_body = request.get_json() + + + # if "title" in updated_body: + # task.title = updated_body["title"] + # elif "description" in updated_body: + # task.description = updated_body["description"] + + task_dict = {} + task_dict = { + "task": { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at is not None + } + } + + return jsonify(task_dict), 200 \ No newline at end of file From 12c4967486b951abe268e88a0ee62f3a65ef934d Mon Sep 17 00:00:00 2001 From: Ngozi Amaefule Date: Thu, 4 Nov 2021 17:09:16 -0400 Subject: [PATCH 3/4] Added Goal model and associated methods --- app/__init__.py | 2 + app/models/goal.py | 1 + app/routes.py | 189 ++++++++++++++++++++++++++- migrations/versions/950b5cdd5a2a_.py | 28 ++++ tests/test_wave_05.py | 48 +++++-- 5 files changed, 258 insertions(+), 10 deletions(-) create mode 100644 migrations/versions/950b5cdd5a2a_.py diff --git a/app/__init__.py b/app/__init__.py index 203d87760..99d278605 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -31,5 +31,7 @@ def create_app(test_config=None): # Register Blueprints here from app.routes import tasks_bp + from app.routes import goals_bp app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..0bdc1731d 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,3 +4,4 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) diff --git a/app/routes.py b/app/routes.py index b2f43b154..16481dfd2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, jsonify, request from flask.helpers import make_response from app.models.task import Task +from app.models.goal import Goal import requests from datetime import datetime # datetime is a Python package so no need for "from datetime" from app import db # Why from app and not app.__init___? @@ -10,7 +11,7 @@ tasks_bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @tasks_bp.route("", methods=["POST"]) -def create_tasks(): +def create_task(): request_body = request.get_json() if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body: @@ -203,4 +204,188 @@ def update_incomplete(task_id): } } - return jsonify(task_dict), 200 \ No newline at end of file + return jsonify(task_dict), 200 + +goals_bp = Blueprint("goals_bp", __name__, url_prefix="/goals") + +@goals_bp.route("", methods=["POST"]) +def create_goal(): + request_body = request.get_json() + + if "title" not in request_body: + return jsonify({"details": "Invalid data"}), 400 + + new_goal = Goal( + title=request_body["title"] + ) + + db.session.add(new_goal) + db.session.commit() + + response_body = { + "goal": { + "id": new_goal.goal_id, + "title": new_goal.title + } + } + + return jsonify(response_body), 201 + +@goals_bp.route("", methods=["GET"]) +def read_goals(): + title_query = request.args.get("sort") + # Is "sort" a keyword? Can you replace it with "low" or "high"? Why not pass in "title"? + # Queries are the records (i.e. rows) + if title_query == "asc": + goals = Goal.query.order_by(Goal.title.asc()) + elif title_query == "desc": + goals = Goal.query.order_by(Goal.title.desc()) + else: + goals = Goal.query.all() + # Because Task is referring to a table, we are capturing all the records (rows) in the table and holding it in tasks. + + goal_responses = [] + for goal in goals: + goal_responses.append( + { + "id": goal.goal_id, + "title": goal.title + } + ) + + return jsonify(goal_responses), 200 + +@goals_bp.route("/", methods=["GET"]) +def read_goal(goal_id): + goal_id = int(goal_id) + goal = Goal.query.get(goal_id) + + goal_dict = {} + if goal == None: + return jsonify(None), 404 + else: + goal_dict = { + "goal": { + "id": goal.goal_id, + "title": goal.title + } + } + + return jsonify(goal_dict), 200 + +@goals_bp.route("/",methods=["PUT"]) +def update_goal(goal_id): + goal_id = int(goal_id) + goal = Goal.query.get(goal_id) + + updated_body = request.get_json() + + if goal == None: + return jsonify(None), 404 + + else: + goal.title = updated_body["title"] + + db.session.commit() + + goal_dict = {} + goal_dict = { + "goal": { + "id": goal.goal_id, + "title": goal.title + } + } + + return jsonify(goal_dict), 200 + +@goals_bp.route("/", methods=["DELETE"]) +def delete_goal(goal_id): + goal_id = int(goal_id) + goal = Goal.query.get(goal_id) + + # deleted_body = request.get_json() + + if goal == None: + return jsonify(None), 404 + + else: + db.session.delete(goal) + db.session.commit() + + response_body = {} + response_body = { + "details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted'} + return jsonify(response_body), 200 + +# def slack_bot(title): +# query_path = {'channel':'slack_api_test_channel', 'text': title} +# header = {'Authorization': os.environ.get('BOT')} +# response = requests.post('https://slack.com/api/chat.postMessage', params = query_path, headers = header) +# return response.json() + +# @goals_bp.route("//mark_complete", methods=["PATCH"]) +# def update_complete(task_id): +# task_id = int(task_id) +# task = Task.query.get(task_id) + +# if task == None: +# return jsonify(None), 404 + +# task.completed_at = datetime.now() +# db.session.commit() + +# slack_bot(task.title) + +# # updated_body = request.get_json() + + +# # if "title" in updated_body: +# # task.title = updated_body["title"] +# # elif "description" in updated_body: +# # task.description = updated_body["description"] +# # elif "completed_at" in updated_body: +# # task.completed_at = updated_body["completed_at"] + +# # db.session.commit() +# # Isn't task updated with the correct/updated title, description, and completed_at at this point? +# task_dict = {} +# task_dict = { +# "task": { +# "id": task.task_id, +# "title": task.title, +# "description": task.description, +# "is_complete": task.completed_at is not None +# } +# } + +# return jsonify(task_dict), 200 + +# @tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +# def update_incomplete(task_id): +# task_id = int(task_id) +# task = Task.query.get(task_id) + +# if task == None: +# return jsonify(None), 404 +# task.completed_at = None + +# db.session.commit() +# # updated_body = request.get_json() + + +# # if "title" in updated_body: +# # task.title = updated_body["title"] +# # elif "description" in updated_body: +# # task.description = updated_body["description"] + +# task_dict = {} +# task_dict = { +# "task": { +# "id": task.task_id, +# "title": task.title, +# "description": task.description, +# "is_complete": task.completed_at is not None +# } +# } + +# return jsonify(task_dict), 200 \ No newline at end of file diff --git a/migrations/versions/950b5cdd5a2a_.py b/migrations/versions/950b5cdd5a2a_.py new file mode 100644 index 000000000..a1b5b29f3 --- /dev/null +++ b/migrations/versions/950b5cdd5a2a_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: 950b5cdd5a2a +Revises: 001991e91f43 +Create Date: 2021-11-04 15:04:03.443481 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '950b5cdd5a2a' +down_revision = '001991e91f43' +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 6ba60c6fa..b0e9f1ed2 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,4 +1,5 @@ import pytest +from app.models.goal import Goal def test_get_goals_no_saved_goals(client): # Act @@ -41,9 +42,7 @@ def test_get_goal(client, one_goal): } } -@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): - pass # Act response = client.get("/goals/1") response_body = response.get_json() @@ -52,6 +51,10 @@ def test_get_goal_not_found(client): # ---- Complete Test ---- # assertion 1 goes here # assertion 2 goes here + # Assert + assert response.status_code == 404 + assert response_body == None + # ---- Complete Test ---- def test_create_goal(client): @@ -71,9 +74,25 @@ def test_create_goal(client): } } -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - pass + # Act + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title" + } + } + goal = Goal.query.get(1) + assert goal.title == "Updated Goal Title" + # Act # ---- Complete Act Here ---- @@ -84,9 +103,16 @@ def test_update_goal(client, one_goal): # assertion 3 goes here # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - pass + # Act + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == None # Act # ---- Complete Act Here ---- @@ -113,9 +139,15 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 -@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - pass + # Act + response = client.delete("/goals/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == None + assert Goal.query.all() == [] # Act # ---- Complete Act Here ---- From 39cf349b4f39518c5a6f6605688536eb126343a8 Mon Sep 17 00:00:00 2001 From: Ngozi Amaefule Date: Mon, 8 Nov 2021 12:58:01 -0500 Subject: [PATCH 4/4] Began refactoring routes.py --- app/models/goal.py | 1 + app/models/task.py | 1 + app/routes.py | 166 +++++++++------------------ migrations/versions/32f1f22df9c1_.py | 30 +++++ 4 files changed, 86 insertions(+), 112 deletions(-) create mode 100644 migrations/versions/32f1f22df9c1_.py diff --git a/app/models/goal.py b/app/models/goal.py index 0bdc1731d..2335366c9 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -5,3 +5,4 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) + tasks = db.relationship('Task', backref='goal', lazy=True) \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index e04ef8404..c17c7c0bb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,3 +8,4 @@ class Task(db.Model): 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) diff --git a/app/routes.py b/app/routes.py index 16481dfd2..927fdbd1d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,10 +1,11 @@ +import re from flask import Blueprint, jsonify, request from flask.helpers import make_response from app.models.task import Task from app.models.goal import Goal import requests -from datetime import datetime # datetime is a Python package so no need for "from datetime" -from app import db # Why from app and not app.__init___? +from datetime import datetime +from app import db import os from dotenv import load_dotenv @@ -23,9 +24,6 @@ def create_task(): completed_at=request_body["completed_at"] ) - # SQLAlachemy has a class named session. Inside that class there is an instane method call add. - # This is telling SQLAlachemy to add new_task to the database. Think of add as a staging process - db.session.add(new_task) db.session.commit() @@ -42,17 +40,15 @@ def create_task(): @tasks_bp.route("", methods=["GET"]) def read_tasks(): - title_query = request.args.get("sort") - # Is "sort" a keyword? Can you replace it with "low" or "high"? Why not pass in "title"? - # Queries are the records (i.e. rows) + title_query = request.args.get("sort") + if title_query == "asc": tasks = Task.query.order_by(Task.title.asc()) elif title_query == "desc": tasks = Task.query.order_by(Task.title.desc()) else: tasks = Task.query.all() - # Because Task is referring to a table, we are capturing all the records (rows) in the table and holding it in tasks. - + task_responses = [] for task in tasks: task_responses.append( @@ -71,20 +67,28 @@ def read_task(task_id): task_id = int(task_id) task = Task.query.get(task_id) - task_dict = {} if task == None: return jsonify(None), 404 - else: - task_dict = { + + if not task.goal_id: + return jsonify({ "task": { - "id": task.task_id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at is not None + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": False if task.completed_at == None else True } - } - - return jsonify(task_dict), 200 + }), 200 + else: + return jsonify({ + "task": { + "id": task.task_id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": False if task.completed_at == None else True + } + }), 200 @tasks_bp.route("/",methods=["PUT"]) def update_task(task_id): @@ -118,8 +122,6 @@ def update_task(task_id): def delete_task(task_id): task_id = int(task_id) task = Task.query.get(task_id) - - # deleted_body = request.get_json() if task == None: return jsonify(None), 404 @@ -152,18 +154,6 @@ def update_complete(task_id): slack_bot(task.title) - # updated_body = request.get_json() - - - # if "title" in updated_body: - # task.title = updated_body["title"] - # elif "description" in updated_body: - # task.description = updated_body["description"] - # elif "completed_at" in updated_body: - # task.completed_at = updated_body["completed_at"] - - # db.session.commit() - # Isn't task updated with the correct/updated title, description, and completed_at at this point? task_dict = {} task_dict = { "task": { @@ -183,17 +173,11 @@ def update_incomplete(task_id): if task == None: return jsonify(None), 404 + task.completed_at = None db.session.commit() - # updated_body = request.get_json() - - # if "title" in updated_body: - # task.title = updated_body["title"] - # elif "description" in updated_body: - # task.description = updated_body["description"] - task_dict = {} task_dict = { "task": { @@ -234,15 +218,13 @@ def create_goal(): @goals_bp.route("", methods=["GET"]) def read_goals(): title_query = request.args.get("sort") - # Is "sort" a keyword? Can you replace it with "low" or "high"? Why not pass in "title"? - # Queries are the records (i.e. rows) + if title_query == "asc": goals = Goal.query.order_by(Goal.title.asc()) elif title_query == "desc": goals = Goal.query.order_by(Goal.title.desc()) else: goals = Goal.query.all() - # Because Task is referring to a table, we are capturing all the records (rows) in the table and holding it in tasks. goal_responses = [] for goal in goals: @@ -303,7 +285,6 @@ def delete_goal(goal_id): goal_id = int(goal_id) goal = Goal.query.get(goal_id) - # deleted_body = request.get_json() if goal == None: return jsonify(None), 404 @@ -317,75 +298,36 @@ def delete_goal(goal_id): "details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted'} return jsonify(response_body), 200 -# def slack_bot(title): -# query_path = {'channel':'slack_api_test_channel', 'text': title} -# header = {'Authorization': os.environ.get('BOT')} -# response = requests.post('https://slack.com/api/chat.postMessage', params = query_path, headers = header) -# return response.json() - -# @goals_bp.route("//mark_complete", methods=["PATCH"]) -# def update_complete(task_id): -# task_id = int(task_id) -# task = Task.query.get(task_id) - -# if task == None: -# return jsonify(None), 404 - -# task.completed_at = datetime.now() -# db.session.commit() - -# slack_bot(task.title) - -# # updated_body = request.get_json() - - -# # if "title" in updated_body: -# # task.title = updated_body["title"] -# # elif "description" in updated_body: -# # task.description = updated_body["description"] -# # elif "completed_at" in updated_body: -# # task.completed_at = updated_body["completed_at"] - -# # db.session.commit() -# # Isn't task updated with the correct/updated title, description, and completed_at at this point? -# task_dict = {} -# task_dict = { -# "task": { -# "id": task.task_id, -# "title": task.title, -# "description": task.description, -# "is_complete": task.completed_at is not None -# } -# } - -# return jsonify(task_dict), 200 +@goals_bp.route("//tasks", methods=["POST", "GET"]) +def create_list(goal_id): + goal_id = int(goal_id) + goal = Goal.query.get(goal_id) -# @tasks_bp.route("//mark_incomplete", methods=["PATCH"]) -# def update_incomplete(task_id): -# task_id = int(task_id) -# task = Task.query.get(task_id) + if goal == None: + return jsonify(None), 404 -# if task == None: -# return jsonify(None), 404 -# task.completed_at = None + if request.method == "POST": + request_body = request.get_json() + task_ids = request_body["task_ids"] -# db.session.commit() -# # updated_body = request.get_json() + for task_id in task_ids: + task = Task.query.get(task_id) + task.goal_id = goal.goal_id + + db.session.commit() + + return jsonify({"id": goal.goal_id, "task_ids": request_body["task_ids"]}), 200 + elif request.method == "GET": + tasks_and_goals = [] -# # if "title" in updated_body: -# # task.title = updated_body["title"] -# # elif "description" in updated_body: -# # task.description = updated_body["description"] - -# task_dict = {} -# task_dict = { -# "task": { -# "id": task.task_id, -# "title": task.title, -# "description": task.description, -# "is_complete": task.completed_at is not None -# } -# } - -# return jsonify(task_dict), 200 \ No newline at end of file + for task in goal.tasks: + tasks_and_goals.append({ + "id": task.task_id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": False if task.completed_at == None else True + }) + + return jsonify({"id": goal.goal_id, "title": goal.title, "tasks": tasks_and_goals}), 200 \ No newline at end of file diff --git a/migrations/versions/32f1f22df9c1_.py b/migrations/versions/32f1f22df9c1_.py new file mode 100644 index 000000000..dae634715 --- /dev/null +++ b/migrations/versions/32f1f22df9c1_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 32f1f22df9c1 +Revises: 950b5cdd5a2a +Create Date: 2021-11-04 19:42:27.855194 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '32f1f22df9c1' +down_revision = '950b5cdd5a2a' +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 ###