From e2a223a6e185a3c5bc7e3410ec9f8421bc5789af Mon Sep 17 00:00:00 2001 From: jae Date: Wed, 11 May 2022 22:54:28 -0500 Subject: [PATCH 01/16] wave one --- app/__init__.py | 6 ++ app/helper_routes.py | 11 +++ app/models/task.py | 71 ++++++++++++++++++- app/routes.py | 101 ++++++++++++++++++++++++++- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++ migrations/script.py.mako | 24 +++++++ migrations/versions/45f920916a1a_.py | 44 ++++++++++++ migrations/versions/79dcc322ebac_.py | 39 +++++++++++ tests/test_wave_01.py | 16 +++-- 11 files changed, 445 insertions(+), 9 deletions(-) create mode 100644 app/helper_routes.py 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/45f920916a1a_.py create mode 100644 migrations/versions/79dcc322ebac_.py diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..ba9e1de6f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,3 +1,4 @@ + from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate @@ -26,9 +27,14 @@ def create_app(test_config=None): from app.models.task import Task from app.models.goal import Goal + + db.init_app(app) migrate.init_app(app, db) + from app.routes import task_bp + app.register_blueprint(task_bp) + # Register Blueprints here return app diff --git a/app/helper_routes.py b/app/helper_routes.py new file mode 100644 index 000000000..7d26ddf7c --- /dev/null +++ b/app/helper_routes.py @@ -0,0 +1,11 @@ + +from flask import jsonify, abort, make_response + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + + + + +# validate record +# pass in the actual class in our function, to use for both models ! \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index c91ab281f..aac8ee0b9 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,74 @@ from app import db +''' +task_id: a primary key for each task +title: text to name the task +description: text to describe the task +completed_at: a datetime that has the date that a +task is completed on. Can be nullable, and contain a +null value. A task with a null value for completed_at has +not been completed. When we create a new task, completed_at +should be null AKA None in Python.''' + class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + is_complete = db.Column(db.Boolean, default=False) + completed_at = db.Column(db.DateTime, default=None) + + + def to_dict(self): + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete + + ) + + def to_dict_one_task(self): + return { + "task": { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": self.is_complete + } + } + + + + + @classmethod + def from_dict(cls, data_dict): + return cls( + title=data_dict["title"], + description=data_dict["description"], + is_complete=data_dict["is_complete"], + + ) + + # def replace_details(self, data_dict): + # self.name=data_dict["name"] + # self.description=data_dict["description"] + # self.life=data_dict["life"] + # self.moons=data_dict["moons"] + # return self.to_dict() + + + + # completed_at : default null (none) + + # is_complete(db.relationship) + + + # when we care a new task, completed_att should be NULL (NONE) + + + + + + + diff --git a/app/routes.py b/app/routes.py index 3aae38d49..2116ae88f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1 +1,100 @@ -from flask import Blueprint \ No newline at end of file +from app import db +from app.models.task import Task +from flask import Blueprint, jsonify, make_response, request, abort +# from app.routes.routes_helper import error_message + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + + +task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") + +def make_task_safely(data_dict): + # return Task.from_dict(data_dict) + + try: + return Task.from_dict(data_dict) + except KeyError as err: + error_message(f"Missing key: {err}", 400) + +@task_bp.route("", methods=["GET"]) +def get_tasks(): + tasks = Task.query.all() + # name_param = request.args.get("name") + + # if name_param: + # tasks = Task.query.filter_by(name=name_param) + # else: + + response_body = [task.to_dict() for task in tasks] + return jsonify(response_body) + +def validate_task(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + + task = Task.query.get(id) + + if task: + return task + error_message(f'task with id #{id} not found', 404) + + + +@task_bp.route("/", methods=["GET"]) +def get_task(id): + task = validate_task(id) + return jsonify(task.to_dict_one_task()) + + +@task_bp.route("/", methods=["DELETE"]) +def delete_task(id): + valid_task = validate_task(id) + task = valid_task.to_dict_one_task() + title = task['task']['title'] + response_body = {"details": f'Task {id} "{title}" successfully deleted'} + + db.session.delete(valid_task) + db.session.commit() + return response_body + + +# +# def error_message(message, status_code): +# abort(make_response(jsonify(dict(details=message)), status_code + + + + + +# @task_bp.route("", methods=("POST",)) +# def create_task(): + +# request_body = request.get_json() +# task = make_task_safely(request_body) + +# request_body = request.get_json() +# new_task = make_task_safely(request_body) + + # db.session.add(task) + # db.session.commit() + + # return jsonify(task.to_dict()), 201 + + # return jsonify(new_task.to_dict()), 201 + + + + + + + + + + + + + + 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/45f920916a1a_.py b/migrations/versions/45f920916a1a_.py new file mode 100644 index 000000000..e6272be03 --- /dev/null +++ b/migrations/versions/45f920916a1a_.py @@ -0,0 +1,44 @@ +"""empty message + +Revision ID: 45f920916a1a +Revises: 79dcc322ebac +Create Date: 2022-05-11 14:11:20.069423 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '45f920916a1a' +down_revision = '79dcc322ebac' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('id', sa.Integer(), nullable=False)) + op.add_column('task', sa.Column('is_complete', sa.Boolean(), nullable=True)) + op.alter_column('task', 'description', + existing_type=sa.VARCHAR(), + nullable=False) + op.alter_column('task', 'title', + existing_type=sa.VARCHAR(), + nullable=False) + op.drop_column('task', 'task_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.alter_column('task', 'title', + existing_type=sa.VARCHAR(), + nullable=True) + op.alter_column('task', 'description', + existing_type=sa.VARCHAR(), + nullable=True) + op.drop_column('task', 'is_complete') + op.drop_column('task', 'id') + # ### end Alembic commands ### diff --git a/migrations/versions/79dcc322ebac_.py b/migrations/versions/79dcc322ebac_.py new file mode 100644 index 000000000..ee2e5d0ce --- /dev/null +++ b/migrations/versions/79dcc322ebac_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 79dcc322ebac +Revises: +Create Date: 2022-05-06 12:57:18.239400 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '79dcc322ebac' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.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 dca626d78..493f40ee2 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") @@ -60,7 +60,9 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == {'details': 'task with id #1 not found'} + + # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -137,7 +139,7 @@ def test_update_task_not_found(client): # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -161,7 +163,7 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + raise Exception("No task with this id exists") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From bfb2572680b334d8dc568f2d92523670a39de4b4 Mon Sep 17 00:00:00 2001 From: jae Date: Wed, 11 May 2022 23:51:56 -0500 Subject: [PATCH 02/16] add first post --- app/models/task.py | 4 ++-- app/routes.py | 31 ++++++++++++++++++------------- tests/test_wave_01.py | 2 +- 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index aac8ee0b9..097c8025d 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -24,7 +24,7 @@ def to_dict(self): id=self.id, title=self.title, description=self.description, - is_complete=self.is_complete + is_complete=self.is_complete ) @@ -46,7 +46,7 @@ def from_dict(cls, data_dict): return cls( title=data_dict["title"], description=data_dict["description"], - is_complete=data_dict["is_complete"], + # is_complete=data_dict["is_complete"], ) diff --git a/app/routes.py b/app/routes.py index 2116ae88f..5e93f924d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,21 +1,18 @@ from app import db from app.models.task import Task from flask import Blueprint, jsonify, make_response, request, abort -# from app.routes.routes_helper import error_message - -def error_message(message, status_code): - abort(make_response(jsonify(dict(details=message)), status_code)) +from app.helper_routes import error_message task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") def make_task_safely(data_dict): - # return Task.from_dict(data_dict) + return Task.from_dict(data_dict) - try: - return Task.from_dict(data_dict) - except KeyError as err: - error_message(f"Missing key: {err}", 400) + # try: + # return Task.from_dict(data_dict) + # except KeyError as err: + # error_message(f"Missing key: {err}", 400) @task_bp.route("", methods=["GET"]) def get_tasks(): @@ -42,6 +39,16 @@ def validate_task(id): error_message(f'task with id #{id} not found', 404) +@task_bp.route("", methods=["POST"]) +def create_task(): + request_body = request.get_json() + new_task = make_task_safely(request_body) + + db.session.add(new_task) + db.session.commit() + + return jsonify(new_task.to_dict_one_task()), 201 + @task_bp.route("/", methods=["GET"]) def get_task(id): @@ -55,15 +62,13 @@ def delete_task(id): task = valid_task.to_dict_one_task() title = task['task']['title'] response_body = {"details": f'Task {id} "{title}" successfully deleted'} - + db.session.delete(valid_task) db.session.commit() return response_body -# -# def error_message(message, status_code): -# abort(make_response(jsonify(dict(details=message)), status_code + diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 493f40ee2..082d3aa5e 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -68,7 +68,7 @@ def test_get_task_not_found(client): # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ From ec31f835bd838680381f226eed779c79adaf88c4 Mon Sep 17 00:00:00 2001 From: jae Date: Thu, 12 May 2022 10:51:07 -0500 Subject: [PATCH 03/16] complete wave 1 --- app/models/task.py | 34 +++++++--------- app/routes.py | 40 ++++++++++++++++++- .../b65b600c5b3a_make_is_complete_not_null.py | 32 +++++++++++++++ .../c11b90305e5a_remove_id_from_dict.py | 32 +++++++++++++++ tests/test_wave_01.py | 14 +++---- 5 files changed, 124 insertions(+), 28 deletions(-) create mode 100644 migrations/versions/b65b600c5b3a_make_is_complete_not_null.py create mode 100644 migrations/versions/c11b90305e5a_remove_id_from_dict.py diff --git a/app/models/task.py b/app/models/task.py index 097c8025d..572fce204 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,18 +1,7 @@ from app import db -''' -task_id: a primary key for each task -title: text to name the task -description: text to describe the task -completed_at: a datetime that has the date that a -task is completed on. Can be nullable, and contain a -null value. A task with a null value for completed_at has -not been completed. When we create a new task, completed_at -should be null AKA None in Python.''' - - class Task(db.Model): - id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) is_complete = db.Column(db.Boolean, default=False) @@ -24,7 +13,8 @@ def to_dict(self): id=self.id, title=self.title, description=self.description, - is_complete=self.is_complete + is_complete=self.is_complete, + ) @@ -34,7 +24,9 @@ def to_dict_one_task(self): "id": self.id, "title": self.title, "description": self.description, - "is_complete": self.is_complete + "is_complete": self.is_complete, + # "completed_at": self.completed_at + # "is_complete": False } } @@ -47,15 +39,17 @@ def from_dict(cls, data_dict): title=data_dict["title"], description=data_dict["description"], # is_complete=data_dict["is_complete"], + # completed_at=data_dict["completed_at"] + # is_complete=data_dict["is_complete"], ) - # def replace_details(self, data_dict): - # self.name=data_dict["name"] - # self.description=data_dict["description"] - # self.life=data_dict["life"] - # self.moons=data_dict["moons"] - # return self.to_dict() + def replace_details(self, data_dict): + self.title=data_dict["title"] + self.description=data_dict["description"] + # self.is_complete=data_dict["is_complete"] + + return self.to_dict() diff --git a/app/routes.py b/app/routes.py index 5e93f924d..7cc631960 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,16 +14,34 @@ def make_task_safely(data_dict): # except KeyError as err: # error_message(f"Missing key: {err}", 400) + +def replace_task_safely(task, data_dict): + return task.replace_details(data_dict) + # try: + # task.replace_details(data_dict) + # except KeyError as err: + # error_message(f"Missing key: {err}", 400) + @task_bp.route("", methods=["GET"]) def get_tasks(): tasks = Task.query.all() + # asc = request.args.get("sort") + # desc = request.args.get("sort") + + response_body = [task.to_dict() for task in tasks] + + # if asc: + # sorted(response_body, key = lambda i:i['title']) + + + # name_param = request.args.get("name") # if name_param: # tasks = Task.query.filter_by(name=name_param) # else: - response_body = [task.to_dict() for task in tasks] + # response_body = [task.to_dict() for task in tasks] return jsonify(response_body) def validate_task(id): @@ -42,8 +60,15 @@ def validate_task(id): @task_bp.route("", methods=["POST"]) def create_task(): request_body = request.get_json() + + + if "title" not in request_body or "description" not in request_body: + return {'details': 'Invalid data'}, 400 + new_task = make_task_safely(request_body) + print(new_task) + db.session.add(new_task) db.session.commit() @@ -56,6 +81,19 @@ def get_task(id): return jsonify(task.to_dict_one_task()) +@task_bp.route("/", methods=["PUT"]) +def update_task_by_id(id): + request_body = request.get_json() + task = validate_task(id) + + replace_task_safely(task, request_body) + db.session.commit() + return jsonify(task.to_dict_one_task()) + + + + + @task_bp.route("/", methods=["DELETE"]) def delete_task(id): valid_task = validate_task(id) diff --git a/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py b/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py new file mode 100644 index 000000000..87849843b --- /dev/null +++ b/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py @@ -0,0 +1,32 @@ +"""make is_complete not null + +Revision ID: b65b600c5b3a +Revises: 45f920916a1a +Create Date: 2022-05-12 08:19:24.322169 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'b65b600c5b3a' +down_revision = '45f920916a1a' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'is_complete', + existing_type=sa.BOOLEAN(), + nullable=False) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'is_complete', + existing_type=sa.BOOLEAN(), + nullable=True) + # ### end Alembic commands ### diff --git a/migrations/versions/c11b90305e5a_remove_id_from_dict.py b/migrations/versions/c11b90305e5a_remove_id_from_dict.py new file mode 100644 index 000000000..e80475497 --- /dev/null +++ b/migrations/versions/c11b90305e5a_remove_id_from_dict.py @@ -0,0 +1,32 @@ +"""remove id from dict + +Revision ID: c11b90305e5a +Revises: b65b600c5b3a +Create Date: 2022-05-12 08:24:04.888053 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c11b90305e5a' +down_revision = 'b65b600c5b3a' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'is_complete', + existing_type=sa.BOOLEAN(), + nullable=True) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'is_complete', + existing_type=sa.BOOLEAN(), + nullable=False) + # ### end Alembic commands ### diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 082d3aa5e..f4e0a8cc1 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -95,7 +95,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={ @@ -121,7 +121,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={ @@ -133,7 +133,7 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "task with id #1 not found"} # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -154,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") @@ -163,7 +163,7 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("No task with this id exists") + assert response_body == {"details": "task with id #1 not found"} # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -171,7 +171,7 @@ def test_delete_task_not_found(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -188,7 +188,7 @@ def test_create_task_must_contain_title(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ From 5e79d2b7178677773f8c313dd4ff7ecb682c340d Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 03:47:27 -0500 Subject: [PATCH 04/16] latest --- app/__init__.py | 15 +- app/helper_routes.py | 1 + app/models/goal.py | 16 +- app/models/task.py | 44 ++-- app/routes.py | 244 +++++++++++++----- migrations/versions/45f920916a1a_.py | 44 ---- migrations/versions/848028ca0487_make_goal.py | 32 +++ ...dcc322ebac_.py => 88f1e2121c63_restart.py} | 17 +- .../b65b600c5b3a_make_is_complete_not_null.py | 32 --- ...9907e59a616_est_goal_task_relationships.py | 32 +++ .../c11b90305e5a_remove_id_from_dict.py | 32 --- tests/test_wave_02.py | 4 +- tests/test_wave_03.py | 20 +- tests/test_wave_05.py | 83 +++--- tests/test_wave_06.py | 4 +- 15 files changed, 369 insertions(+), 251 deletions(-) delete mode 100644 migrations/versions/45f920916a1a_.py create mode 100644 migrations/versions/848028ca0487_make_goal.py rename migrations/versions/{79dcc322ebac_.py => 88f1e2121c63_restart.py} (65%) delete mode 100644 migrations/versions/b65b600c5b3a_make_is_complete_not_null.py create mode 100644 migrations/versions/b9907e59a616_est_goal_task_relationships.py delete mode 100644 migrations/versions/c11b90305e5a_remove_id_from_dict.py diff --git a/app/__init__.py b/app/__init__.py index ba9e1de6f..33c919eef 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,8 +2,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() @@ -23,17 +23,20 @@ def create_app(test_config=None): app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") + # db.init_app(app) + # migrate.init_app(app, db) + # Import models here for Alembic setup from app.models.task import Task from app.models.goal import Goal - - db.init_app(app) - migrate.init_app(app, db) - - from app.routes import task_bp + migrate.init_app(app, db) + + from .routes import task_bp, goal_bp app.register_blueprint(task_bp) + app.register_blueprint(goal_bp) + # Register Blueprints here diff --git a/app/helper_routes.py b/app/helper_routes.py index 7d26ddf7c..ba10f64bd 100644 --- a/app/helper_routes.py +++ b/app/helper_routes.py @@ -1,4 +1,5 @@ + from flask import jsonify, abort, make_response def error_message(message, status_code): diff --git a/app/models/goal.py b/app/models/goal.py index b0ed11dd8..f84feba3e 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,4 +2,18 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String, nullable=False) + tasks = db.relationship('Task', backref='goal', lazy=True) + + + def to_dict(self): + return dict( + id=self.id, + title=self.title) + + + + +## ONE TO MANY RELATIONSHIP +# GOALS HAVE MANY TASKS diff --git a/app/models/task.py b/app/models/task.py index 572fce204..f94b50202 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,11 +1,14 @@ from app import db class Task(db.Model): - id = db.Column(db.Integer, primary_key=True, autoincrement=True) + id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) - is_complete = db.Column(db.Boolean, default=False) + # is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime, default=None) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.id')) + # goal = db.relationship ("Goal", backref='tasks') + def to_dict(self): @@ -13,31 +16,27 @@ def to_dict(self): id=self.id, title=self.title, description=self.description, - is_complete=self.is_complete, - - + is_complete=True if self.completed_at else False ) - def to_dict_one_task(self): - return { - "task": { - "id": self.id, - "title": self.title, - "description": self.description, - "is_complete": self.is_complete, - # "completed_at": self.completed_at - # "is_complete": False - } - } + # def to_dict_one_task(self): + # return { + # "task": { + # "id": self.id, + # "title": self.title, + # "description": self.description, + # "is_complete": self.is_complete + # # "completed_at": self.completed_at + # # "is_complete": False + # } + # } - - - @classmethod def from_dict(cls, data_dict): + return cls( title=data_dict["title"], - description=data_dict["description"], + description=data_dict["description"] # is_complete=data_dict["is_complete"], # completed_at=data_dict["completed_at"] # is_complete=data_dict["is_complete"], @@ -47,7 +46,10 @@ def from_dict(cls, data_dict): def replace_details(self, data_dict): self.title=data_dict["title"] self.description=data_dict["description"] - # self.is_complete=data_dict["is_complete"] + + if "completed_at" in data_dict: + self.completed_at=data_dict["completed_at"] + self.is_complete= True return self.to_dict() diff --git a/app/routes.py b/app/routes.py index 7cc631960..4fc6fd26b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,48 +1,51 @@ from app import db -from app.models.task import Task -from flask import Blueprint, jsonify, make_response, request, abort +from app.models.task import Task +from app.models.goal import Goal +from flask import Blueprint, jsonify, make_response, request, abort, Response from app.helper_routes import error_message +import os +from datetime import datetime +import requests + + + +slack_url = "https://slack.com/api/chat.postMessage" +slack_bot_token= os.environ.get("SLACK_BOT_TOKEN") + task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goal_bp = Blueprint("goals", __name__, url_prefix="/goals") -def make_task_safely(data_dict): - return Task.from_dict(data_dict) +### NEW ROUTE!! ## - # try: - # return Task.from_dict(data_dict) - # except KeyError as err: - # error_message(f"Missing key: {err}", 400) -def replace_task_safely(task, data_dict): - return task.replace_details(data_dict) - # try: - # task.replace_details(data_dict) - # except KeyError as err: - # error_message(f"Missing key: {err}", 400) +@goal_bp.route("", methods=["GET"]) +def get_all_goals(): + goals = Goal.query.all() + response_body = [goal.to_dict() for goal in goals] + return jsonify(response_body) + + @task_bp.route("", methods=["GET"]) -def get_tasks(): - tasks = Task.query.all() - # asc = request.args.get("sort") - # desc = request.args.get("sort") +def get_all_tasks(): + sort_tasks = request.args.get('sort') + - response_body = [task.to_dict() for task in tasks] + if not sort_tasks: + tasks = Task.query.all() + elif sort_tasks == "asc": + tasks = Task.query.order_by(Task.title.asc()).all() + elif sort_tasks == "desc": + tasks = Task.query.order_by(Task.title.desc()).all() + else: + tasks = Task.query.all() - # if asc: - # sorted(response_body, key = lambda i:i['title']) - - - - # name_param = request.args.get("name") + response_body = [task.to_dict() for task in tasks] + return jsonify(response_body) - # if name_param: - # tasks = Task.query.filter_by(name=name_param) - # else: - - # response_body = [task.to_dict() for task in tasks] - return jsonify(response_body) def validate_task(id): try: @@ -56,77 +59,196 @@ def validate_task(id): return task error_message(f'task with id #{id} not found', 404) +def validate_goal(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + + goal = Goal.query.get(id) + + if goal: + return goal + error_message(f'Goal with id #{id} not found', 404) + +def make_task_safely(data_dict): + return Task.from_dict(data_dict) + + +@goal_bp.route("", methods=["POST"]) +def create_goal(): + request_body= request.get_json() + + if "title" not in request_body: + return {'details': 'Invalid data'}, 400 + + new_goal = Goal( + title = request_body.get("title")) + + db.session.add(new_goal) + db.session.commit() + return {"goal": new_goal.to_dict()}, 201 + + + + + @task_bp.route("", methods=["POST"]) -def create_task(): - request_body = request.get_json() +def create_task(): + request_body = request.get_json() + # return request_body if "title" not in request_body or "description" not in request_body: return {'details': 'Invalid data'}, 400 - new_task = make_task_safely(request_body) - - print(new_task) + new_task = Task( + title = request_body.get("title"), + description = request_body.get("description"), + # is_complete=True if "completed_at" in request_body else False + ) + # if "completed_at" in request_body: + # new_task.is_complete=request_body['is_complete'] + print("new_task", new_task) + db.session.add(new_task) db.session.commit() - - return jsonify(new_task.to_dict_one_task()), 201 + return {"task": new_task.to_dict()}, 201 @task_bp.route("/", methods=["GET"]) def get_task(id): task = validate_task(id) - return jsonify(task.to_dict_one_task()) + response_body = {"task": task.to_dict()} + return response_body + +@goal_bp.route("/", methods=["GET"]) +def get_goal(id): + goal = validate_goal(id) + return {"goal": goal.to_dict()} + + + +def replace_task_safely(task, data_dict): + return task.replace_details(data_dict) + # try: + # task.replace_details(data_dict) + # except KeyError as err: + # error_message(f"Missing key: {err}", 400) @task_bp.route("/", methods=["PUT"]) def update_task_by_id(id): request_body = request.get_json() task = validate_task(id) - + replace_task_safely(task, request_body) + db.session.add(task) db.session.commit() - return jsonify(task.to_dict_one_task()) + return {"task": task.to_dict()} +@goal_bp.route("/", methods=["PUT"]) +def update_goal_by_id(id): + goal = validate_goal(id) + request_body = request.get_json() + goal.title = request_body['title'] + + db.session.add(goal) + db.session.commit() + return {"goal": goal.to_dict()} + +@goal_bp.route("//tasks", methods=["POST"]) +def make_tasks_of_a_goal(id): + goal = validate_goal(id) + request_body= request.get_json() + if "task_ids" not in request_body: + return {'details': 'Invalid data'}, 400 + goal.tasks = [Task.query.get(id) for task in "task_ids"] -@task_bp.route("/", methods=["DELETE"]) -def delete_task(id): - valid_task = validate_task(id) - task = valid_task.to_dict_one_task() - title = task['task']['title'] - response_body = {"details": f'Task {id} "{title}" successfully deleted'} + # goal_tasks= { + # "id": goal.id, + # "task_ids" : request_body["task_ids"] + # } - db.session.delete(valid_task) + # for id in request_body["task_ids"]: + # task = Task.query.get(id) + # goal.tasks.append(task) + db.session.commit() - return response_body + return {"task_ids": {goal.tasks}} + + - + + -# @task_bp.route("", methods=("POST",)) -# def create_task(): - -# request_body = request.get_json() -# task = make_task_safely(request_body) -# request_body = request.get_json() -# new_task = make_task_safely(request_body) +@task_bp.route("//mark_complete", methods=["PATCH"]) +def mark_complete(id): + task = validate_task(id) + task.is_complete = True + task.completed_at = datetime.utcnow() + + db.session.commit() + headers = { + "Authorization": f"Bearer {slack_bot_token}", + } + data = { + "channel": "test-channel", + "text": "Task {task.title} has been marked complete", + } + + return {"task": task.to_dict()} + +@task_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_incomplete(id): + task = validate_task(id) + task.is_complete = False + task.completed_at = None + + db.session.commit() + headers = { + "Authorization": f"Bearer {slack_bot_token}", + } + data = { + "channel": "test-channel", + "text": f"Task {task.title} has been marked incomplete", + } + return {"task": task.to_dict()} - # db.session.add(task) - # db.session.commit() - # return jsonify(task.to_dict()), 201 +@task_bp.route("/", methods=["DELETE"]) +def delete_task(id): + task = validate_task(id) + + response_body = {"details": f'Task {task.id} "{task.title}" successfully deleted'} + + db.session.delete(task) + db.session.commit() + return response_body + + + +@goal_bp.route("/", methods=["DELETE"]) +def delete_goal(id): + goal = validate_goal(id) + + response_body = {"details": f'Goal {goal.id} "{goal.title}" successfully deleted'} + + db.session.delete(goal) + db.session.commit() + return response_body - # return jsonify(new_task.to_dict()), 201 diff --git a/migrations/versions/45f920916a1a_.py b/migrations/versions/45f920916a1a_.py deleted file mode 100644 index e6272be03..000000000 --- a/migrations/versions/45f920916a1a_.py +++ /dev/null @@ -1,44 +0,0 @@ -"""empty message - -Revision ID: 45f920916a1a -Revises: 79dcc322ebac -Create Date: 2022-05-11 14:11:20.069423 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '45f920916a1a' -down_revision = '79dcc322ebac' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('id', sa.Integer(), nullable=False)) - op.add_column('task', sa.Column('is_complete', sa.Boolean(), nullable=True)) - op.alter_column('task', 'description', - existing_type=sa.VARCHAR(), - nullable=False) - op.alter_column('task', 'title', - existing_type=sa.VARCHAR(), - nullable=False) - op.drop_column('task', 'task_id') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('task_id', sa.INTEGER(), autoincrement=True, nullable=False)) - op.alter_column('task', 'title', - existing_type=sa.VARCHAR(), - nullable=True) - op.alter_column('task', 'description', - existing_type=sa.VARCHAR(), - nullable=True) - op.drop_column('task', 'is_complete') - op.drop_column('task', 'id') - # ### end Alembic commands ### diff --git a/migrations/versions/848028ca0487_make_goal.py b/migrations/versions/848028ca0487_make_goal.py new file mode 100644 index 000000000..86bda86af --- /dev/null +++ b/migrations/versions/848028ca0487_make_goal.py @@ -0,0 +1,32 @@ +"""make goal + +Revision ID: 848028ca0487 +Revises: 88f1e2121c63 +Create Date: 2022-05-13 01:16:30.304978 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '848028ca0487' +down_revision = '88f1e2121c63' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False)) + op.add_column('goal', sa.Column('title', sa.String(), nullable=False)) + op.drop_column('goal', 'goal_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('goal', 'title') + op.drop_column('goal', 'id') + # ### end Alembic commands ### diff --git a/migrations/versions/79dcc322ebac_.py b/migrations/versions/88f1e2121c63_restart.py similarity index 65% rename from migrations/versions/79dcc322ebac_.py rename to migrations/versions/88f1e2121c63_restart.py index ee2e5d0ce..f0d12505c 100644 --- a/migrations/versions/79dcc322ebac_.py +++ b/migrations/versions/88f1e2121c63_restart.py @@ -1,8 +1,8 @@ -"""empty message +"""restart -Revision ID: 79dcc322ebac +Revision ID: 88f1e2121c63 Revises: -Create Date: 2022-05-06 12:57:18.239400 +Create Date: 2022-05-12 12:48:05.466423 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '79dcc322ebac' +revision = '88f1e2121c63' down_revision = None branch_labels = None depends_on = None @@ -23,11 +23,12 @@ def upgrade(): 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('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('is_complete', sa.Boolean(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('task_id') + sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### diff --git a/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py b/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py deleted file mode 100644 index 87849843b..000000000 --- a/migrations/versions/b65b600c5b3a_make_is_complete_not_null.py +++ /dev/null @@ -1,32 +0,0 @@ -"""make is_complete not null - -Revision ID: b65b600c5b3a -Revises: 45f920916a1a -Create Date: 2022-05-12 08:19:24.322169 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'b65b600c5b3a' -down_revision = '45f920916a1a' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('task', 'is_complete', - existing_type=sa.BOOLEAN(), - nullable=False) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('task', 'is_complete', - existing_type=sa.BOOLEAN(), - nullable=True) - # ### end Alembic commands ### diff --git a/migrations/versions/b9907e59a616_est_goal_task_relationships.py b/migrations/versions/b9907e59a616_est_goal_task_relationships.py new file mode 100644 index 000000000..8ce085420 --- /dev/null +++ b/migrations/versions/b9907e59a616_est_goal_task_relationships.py @@ -0,0 +1,32 @@ +"""est goal task relationships + +Revision ID: b9907e59a616 +Revises: 848028ca0487 +Create Date: 2022-05-13 02:36:31.346864 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'b9907e59a616' +down_revision = '848028ca0487' +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'], ['id']) + op.drop_column('task', 'is_complete') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('is_complete', sa.BOOLEAN(), autoincrement=False, nullable=True)) + op.drop_constraint(None, 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### diff --git a/migrations/versions/c11b90305e5a_remove_id_from_dict.py b/migrations/versions/c11b90305e5a_remove_id_from_dict.py deleted file mode 100644 index e80475497..000000000 --- a/migrations/versions/c11b90305e5a_remove_id_from_dict.py +++ /dev/null @@ -1,32 +0,0 @@ -"""remove id from dict - -Revision ID: c11b90305e5a -Revises: b65b600c5b3a -Create Date: 2022-05-12 08:24:04.888053 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'c11b90305e5a' -down_revision = 'b65b600c5b3a' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('task', 'is_complete', - existing_type=sa.BOOLEAN(), - nullable=True) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('task', 'is_complete', - existing_type=sa.BOOLEAN(), - nullable=False) - # ### end Alembic commands ### diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..651e3aebd 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 959176ceb..85e524fd9 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -42,7 +42,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -62,7 +62,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +99,7 @@ def test_mark_complete_on_completed_task(client, completed_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -119,7 +119,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -128,7 +128,7 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "task with id #1 not found"} # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -143,7 +143,7 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "task with id #1 not found"} # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -151,8 +151,8 @@ def test_mark_incomplete_missing_task(client): # Let's add this test for creating tasks, now that # the completion functionality has been implemented -@pytest.mark.skip(reason="No way to test this feature yet") -def test_create_task_with_valid_completed_at(client): +# @pytest.mark.skip(reason="No way to test this feature yet") +# def test_create_task_with_valid_completed_at(client): # Act response = client.post("/tasks", json={ "title": "A Brand New Task", @@ -181,7 +181,7 @@ def test_create_task_with_valid_completed_at(client): # Let's add this test for updating tasks, now that # the completion functionality has been implemented -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_with_completed_at_date(client, completed_task): # Act response = client.put("/tasks/1", json={ diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..c741a8d3e 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,8 @@ import pytest +from app.models.goal import 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_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,8 +30,8 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") -def test_get_goal(client, one_goal): +# @pytest.mark.skip(reason="No way to test this feature yet") +def test_get_goal_not_found(client, one_goal): # Act response = client.get("/goals/1") response_body = response.get_json() @@ -46,14 +47,14 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") -def test_get_goal_not_found(client): - pass +# @pytest.mark.skip(reason="test to be completed by student") +def test_get_goal_none_found(client): # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + assert response.status_code == 404 + assert response_body == {'details': 'Goal with id #1 not found'} # Assert # ---- Complete Test ---- # assertion 1 goes here @@ -61,7 +62,7 @@ def test_get_goal_not_found(client): # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,23 +81,39 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "New Year, New Goal" }) + + response_body = response.get_json() - # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "New Year, New Goal" + } + } + goal = Goal.query.get(1) + assert goal.title == "New Year, New Goal" + -@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") + response = client.put("/goals/1", json={ + "title": "Read Every Book" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + + assert response_body == {"details": "Goal with id #1 not found"} + + # Act # ---- Complete Act Here ---- @@ -107,7 +124,7 @@ def test_update_goal_not_found(client): # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -119,32 +136,34 @@ def test_delete_goal(client, one_goal): assert response_body == { "details": 'Goal 1 "Build a habit of going outside daily" successfully deleted' } + assert Goal.query.get(1) == None # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 + assert Goal.query.get(1) == None - 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") - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + + assert response_body == {"details": "Goal with id #1 not found"} + assert Goal.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_goal_missing_title(client): # Act response = client.post("/goals", json={}) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..7fd92d92f 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={ @@ -15,7 +15,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert "id" in response_body assert "task_ids" in response_body assert response_body == { - "id": 1, + # "id": 1, "task_ids": [1, 2, 3] } From edeab94951e1690f3f382528f3f383142a02b1c8 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 11:35:21 -0500 Subject: [PATCH 05/16] ost recent, all but 1 test passing --- app/models/task.py | 30 +++++++++-------- app/routes.py | 78 ++++++++++++++++++++++++++++--------------- tests/test_wave_03.py | 2 +- tests/test_wave_06.py | 14 ++++---- 4 files changed, 76 insertions(+), 48 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index f94b50202..2fbf87584 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -4,7 +4,7 @@ class Task(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) - # is_complete = db.Column(db.Boolean, default=False) + is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime, default=None) goal_id = db.Column(db.Integer, db.ForeignKey('goal.id')) # goal = db.relationship ("Goal", backref='tasks') @@ -12,24 +12,26 @@ class Task(db.Model): def to_dict(self): - return dict( + task_dict = dict( + # goal_id=self.goal_id id=self.id, title=self.title, description=self.description, - is_complete=True if self.completed_at else False + is_complete= self.is_complete ) - # def to_dict_one_task(self): - # return { - # "task": { - # "id": self.id, - # "title": self.title, - # "description": self.description, - # "is_complete": self.is_complete - # # "completed_at": self.completed_at - # # "is_complete": False - # } - # } + # True if self.completed_at else False + + if self.completed_at: + task_dict['is_complete'] = True + + if self.goal_id: + task_dict['goal_id'] = self.goal_id + + return task_dict + + + @classmethod def from_dict(cls, data_dict): diff --git a/app/routes.py b/app/routes.py index 4fc6fd26b..d7d2dbc5d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,7 +17,7 @@ task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") goal_bp = Blueprint("goals", __name__, url_prefix="/goals") -### NEW ROUTE!! ## + @@ -45,6 +45,41 @@ def get_all_tasks(): response_body = [task.to_dict() for task in tasks] return jsonify(response_body) + +@goal_bp.route("//tasks", methods=["GET"]) +def get_tasks_for_goal(id): + goal = validate_goal(id) + + task_of_goal = [] + + goal_with_tasks = {"id": goal.id, + "title": goal.title, + "tasks": task_of_goal} + + # if not goal.tasks: + # error_message(f'No tasks associated with this goal', 404) + + + for task in goal.tasks: + task = validate_task(id) + + task_of_goal.append(task.to_dict()) + + print(goal_with_tasks, "MY ANS!!!") + + return goal_with_tasks + + + + + + + + # task_list = [task.to_dict() for task in task_list] + + # return {goal.to_dict(), "tasks": [task_list]} + + def validate_task(id): @@ -159,40 +194,31 @@ def update_goal_by_id(id): db.session.add(goal) db.session.commit() return {"goal": goal.to_dict()} - + @goal_bp.route("//tasks", methods=["POST"]) -def make_tasks_of_a_goal(id): +def tasks_of_goal(id): goal = validate_goal(id) + request_body = request.get_json() - request_body= request.get_json() - if "task_ids" not in request_body: - return {'details': 'Invalid data'}, 400 + # if "task_ids" not in request_body: + # return {'details': 'Invalid data'}, 404 + - goal.tasks = [Task.query.get(id) for task in "task_ids"] + # goal_task = {"id" : goal.id, + # "task_ids": request_body['task_ids']} - # goal_tasks= { - # "id": goal.id, - # "task_ids" : request_body["task_ids"] - # } + # print(request_body['task_ids'], "SHOULD BE A LIST OF NUMBERS **") + + for id in request_body['task_ids']: + new_task = validate_task(id) + goal.tasks.append(new_task) - # for id in request_body["task_ids"]: - # task = Task.query.get(id) - # goal.tasks.append(task) - db.session.commit() - return {"task_ids": {goal.tasks}} + return {"id": goal.id, + "task_ids" : request_body['task_ids']} + - - - - - - - - - - @task_bp.route("//mark_complete", methods=["PATCH"]) def mark_complete(id): task = validate_task(id) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 85e524fd9..348eb1cd3 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -134,7 +134,7 @@ def test_mark_complete_missing_task(client): # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 7fd92d92f..49817d232 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -15,7 +15,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert "id" in response_body assert "task_ids" in response_body assert response_body == { - # "id": 1, + "id": 1, "task_ids": [1, 2, 3] } @@ -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") @@ -51,13 +51,13 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == {'details': 'Goal with id #1 not found'} # ***************************************************************** # **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 318e5c6b9742c0800301466d3d3498a2a57d58e2 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 12:06:43 -0500 Subject: [PATCH 06/16] an update --- app/routes.py | 37 +++++-------------------------------- 1 file changed, 5 insertions(+), 32 deletions(-) diff --git a/app/routes.py b/app/routes.py index d7d2dbc5d..6610881d6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,7 +33,6 @@ def get_all_goals(): def get_all_tasks(): sort_tasks = request.args.get('sort') - if not sort_tasks: tasks = Task.query.all() elif sort_tasks == "asc": @@ -56,9 +55,6 @@ def get_tasks_for_goal(id): "title": goal.title, "tasks": task_of_goal} - # if not goal.tasks: - # error_message(f'No tasks associated with this goal', 404) - for task in goal.tasks: task = validate_task(id) @@ -69,18 +65,6 @@ def get_tasks_for_goal(id): return goal_with_tasks - - - - - - - # task_list = [task.to_dict() for task in task_list] - - # return {goal.to_dict(), "tasks": [task_list]} - - - def validate_task(id): try: @@ -168,10 +152,7 @@ def get_goal(id): def replace_task_safely(task, data_dict): return task.replace_details(data_dict) - # try: - # task.replace_details(data_dict) - # except KeyError as err: - # error_message(f"Missing key: {err}", 400) + @task_bp.route("/", methods=["PUT"]) @@ -200,15 +181,6 @@ def tasks_of_goal(id): goal = validate_goal(id) request_body = request.get_json() - # if "task_ids" not in request_body: - # return {'details': 'Invalid data'}, 404 - - - # goal_task = {"id" : goal.id, - # "task_ids": request_body['task_ids']} - - # print(request_body['task_ids'], "SHOULD BE A LIST OF NUMBERS **") - for id in request_body['task_ids']: new_task = validate_task(id) goal.tasks.append(new_task) @@ -239,16 +211,17 @@ def mark_complete(id): @task_bp.route("//mark_incomplete", methods=["PATCH"]) def mark_incomplete(id): task = validate_task(id) - task.is_complete = False task.completed_at = None + task.is_complete = False + db.session.commit() headers = { - "Authorization": f"Bearer {slack_bot_token}", + "authorization": f"Bearer {slack_bot_token}", } data = { "channel": "test-channel", - "text": f"Task {task.title} has been marked incomplete", + "text": f"Task {task.title} is not complete", } return {"task": task.to_dict()} From 446479aa9f54a9d03c83b6b435670b67185373c4 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 13:36:11 -0500 Subject: [PATCH 07/16] url update --- app/routes.py | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6610881d6..516df8765 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,9 +9,13 @@ -slack_url = "https://slack.com/api/chat.postMessage" + +slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' slack_bot_token= os.environ.get("SLACK_BOT_TOKEN") +channel_name = 'test-channel' +text="Someone just completed the task : {task.title}" + task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") @@ -196,15 +200,13 @@ def mark_complete(id): task = validate_task(id) task.is_complete = True task.completed_at = datetime.utcnow() + + headers = {"Authorization": slack_bot_token} + db.session.commit() - headers = { - "Authorization": f"Bearer {slack_bot_token}", - } - data = { - "channel": "test-channel", - "text": "Task {task.title} has been marked complete", - } + + response = requests.post(slack_url, headers=headers) return {"task": task.to_dict()} @@ -216,10 +218,21 @@ def mark_incomplete(id): db.session.commit() + response = requests.patch(slack_url, params=query_params) + + headers = { + "authorization": f"Bearer {slack_bot_token}", + } + params = { + "channel": "test-channel", + "text": f"Task {task.title} is not complete", + } + + } headers = { "authorization": f"Bearer {slack_bot_token}", } - data = { + params = { "channel": "test-channel", "text": f"Task {task.title} is not complete", } From f6decf5eb60483a9552ea0cec27722ee60d17141 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 14:12:38 -0500 Subject: [PATCH 08/16] slack stuff --- app/models/task.py | 2 +- app/routes.py | 56 ++++++++++++++++++++++------------------------ 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 2fbf87584..d1eec0eee 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -7,7 +7,7 @@ class Task(db.Model): is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime, default=None) goal_id = db.Column(db.Integer, db.ForeignKey('goal.id')) - # goal = db.relationship ("Goal", backref='tasks') + goal = db.relationship ("Goal", backref='tasks') diff --git a/app/routes.py b/app/routes.py index 516df8765..d751f7b1a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -10,14 +10,6 @@ -slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' -slack_bot_token= os.environ.get("SLACK_BOT_TOKEN") - -channel_name = 'test-channel' -text="Someone just completed the task : {task.title}" - - - task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") goal_bp = Blueprint("goals", __name__, url_prefix="/goals") @@ -192,17 +184,23 @@ def tasks_of_goal(id): db.session.commit() return {"id": goal.id, "task_ids" : request_body['task_ids']} - - + + + + @task_bp.route("//mark_complete", methods=["PATCH"]) def mark_complete(id): task = validate_task(id) task.is_complete = True task.completed_at = datetime.utcnow() - + channel_name = 'test-channel' + text="Someone just completed the task : {task.title}" headers = {"Authorization": slack_bot_token} + slack_bot_token= os.environ.get("SLACK_BOT_TOKEN") + slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' + db.session.commit() @@ -218,24 +216,24 @@ def mark_incomplete(id): db.session.commit() - response = requests.patch(slack_url, params=query_params) - - headers = { - "authorization": f"Bearer {slack_bot_token}", - } - params = { - "channel": "test-channel", - "text": f"Task {task.title} is not complete", - } - - } - headers = { - "authorization": f"Bearer {slack_bot_token}", - } - params = { - "channel": "test-channel", - "text": f"Task {task.title} is not complete", - } + # response = requests.patch(slack_url, params=query_params) + + # headers = { + # "authorization": f"Bearer {slack_bot_token}", + # } + # params = { + # "channel": "test-channel", + # "text": f"Task {task.title} is not complete", + # } + + # } + # headers = { + # "authorization": f"Bearer {slack_bot_token}", + # } + # params = { + # "channel": "test-channel", + # "text": f"Task {task.title} is not complete", + # } return {"task": task.to_dict()} From 6ac0d3b41badeacc4ea8fc54cf2f82e9a5439513 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 16:58:58 -0500 Subject: [PATCH 09/16] create slack messages for complete/incomplete --- app/models/task.py | 2 +- app/routes.py | 69 +++++++++---------- migrations/versions/848028ca0487_make_goal.py | 32 --------- ...f1e2121c63_restart.py => 90e88909c11f_.py} | 15 ++-- ...9907e59a616_est_goal_task_relationships.py | 32 --------- tests/test_wave_03.py | 2 +- 6 files changed, 45 insertions(+), 107 deletions(-) delete mode 100644 migrations/versions/848028ca0487_make_goal.py rename migrations/versions/{88f1e2121c63_restart.py => 90e88909c11f_.py} (68%) delete mode 100644 migrations/versions/b9907e59a616_est_goal_task_relationships.py diff --git a/app/models/task.py b/app/models/task.py index d1eec0eee..2fbf87584 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -7,7 +7,7 @@ class Task(db.Model): is_complete = db.Column(db.Boolean, default=False) completed_at = db.Column(db.DateTime, default=None) goal_id = db.Column(db.Integer, db.ForeignKey('goal.id')) - goal = db.relationship ("Goal", backref='tasks') + # goal = db.relationship ("Goal", backref='tasks') diff --git a/app/routes.py b/app/routes.py index d751f7b1a..733c9057a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -105,10 +105,6 @@ def create_goal(): return {"goal": new_goal.to_dict()}, 201 - - - - @task_bp.route("", methods=["POST"]) def create_task(): request_body = request.get_json() @@ -121,12 +117,8 @@ def create_task(): new_task = Task( title = request_body.get("title"), description = request_body.get("description"), - # is_complete=True if "completed_at" in request_body else False + completed_at = request_body.get("completed_at") ) - # if "completed_at" in request_body: - # new_task.is_complete=request_body['is_complete'] - - print("new_task", new_task) db.session.add(new_task) db.session.commit() @@ -185,6 +177,12 @@ def tasks_of_goal(id): return {"id": goal.id, "task_ids" : request_body['task_ids']} +# slack_bot_token= os.environ.put('SLACK_BOT_TOKEN') +# channel_name = 'test-channel' +# text=f"Someone just completed the task a task" +# headers = {"Authorization": slack_bot_token} +# slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' + @@ -192,48 +190,49 @@ def tasks_of_goal(id): @task_bp.route("//mark_complete", methods=["PATCH"]) def mark_complete(id): task = validate_task(id) - task.is_complete = True + # task.is_complete = True task.completed_at = datetime.utcnow() + + db.session.add(task) + db.session.commit() + + # print("TASK TITLE **", task.title) + + # task_dict = task.to_dict() + # print("TASK_DICT TITLE", task_dict.title) + + + + slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') channel_name = 'test-channel' - text="Someone just completed the task : {task.title}" + text=f"Someone just completed {task.title}" headers = {"Authorization": slack_bot_token} - slack_bot_token= os.environ.get("SLACK_BOT_TOKEN") slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' - - db.session.commit() - response = requests.post(slack_url, headers=headers) + + return {"task": task.to_dict()} @task_bp.route("//mark_incomplete", methods=["PATCH"]) def mark_incomplete(id): task = validate_task(id) + task.completed_at = None - task.is_complete = False - + db.session.add(task) db.session.commit() - # response = requests.patch(slack_url, params=query_params) - - # headers = { - # "authorization": f"Bearer {slack_bot_token}", - # } - # params = { - # "channel": "test-channel", - # "text": f"Task {task.title} is not complete", - # } - - # } - # headers = { - # "authorization": f"Bearer {slack_bot_token}", - # } - # params = { - # "channel": "test-channel", - # "text": f"Task {task.title} is not complete", - # } + + slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') + channel_name = 'test-channel' + text=f"Someone still hasn't completed {task.title}" + headers = {"Authorization": slack_bot_token} + slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' + + response = requests.post(slack_url, headers=headers) + return {"task": task.to_dict()} diff --git a/migrations/versions/848028ca0487_make_goal.py b/migrations/versions/848028ca0487_make_goal.py deleted file mode 100644 index 86bda86af..000000000 --- a/migrations/versions/848028ca0487_make_goal.py +++ /dev/null @@ -1,32 +0,0 @@ -"""make goal - -Revision ID: 848028ca0487 -Revises: 88f1e2121c63 -Create Date: 2022-05-13 01:16:30.304978 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '848028ca0487' -down_revision = '88f1e2121c63' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('goal', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False)) - op.add_column('goal', sa.Column('title', sa.String(), nullable=False)) - op.drop_column('goal', 'goal_id') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('goal', sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False)) - op.drop_column('goal', 'title') - op.drop_column('goal', 'id') - # ### end Alembic commands ### diff --git a/migrations/versions/88f1e2121c63_restart.py b/migrations/versions/90e88909c11f_.py similarity index 68% rename from migrations/versions/88f1e2121c63_restart.py rename to migrations/versions/90e88909c11f_.py index f0d12505c..2fefacec6 100644 --- a/migrations/versions/88f1e2121c63_restart.py +++ b/migrations/versions/90e88909c11f_.py @@ -1,8 +1,8 @@ -"""restart +"""empty message -Revision ID: 88f1e2121c63 +Revision ID: 90e88909c11f Revises: -Create Date: 2022-05-12 12:48:05.466423 +Create Date: 2022-05-13 14:14:51.694797 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '88f1e2121c63' +revision = '90e88909c11f' down_revision = None branch_labels = None depends_on = None @@ -19,8 +19,9 @@ 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') + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('id') ) op.create_table('task', sa.Column('id', sa.Integer(), nullable=False), @@ -28,6 +29,8 @@ def upgrade(): sa.Column('description', sa.String(), nullable=False), sa.Column('is_complete', sa.Boolean(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### diff --git a/migrations/versions/b9907e59a616_est_goal_task_relationships.py b/migrations/versions/b9907e59a616_est_goal_task_relationships.py deleted file mode 100644 index 8ce085420..000000000 --- a/migrations/versions/b9907e59a616_est_goal_task_relationships.py +++ /dev/null @@ -1,32 +0,0 @@ -"""est goal task relationships - -Revision ID: b9907e59a616 -Revises: 848028ca0487 -Create Date: 2022-05-13 02:36:31.346864 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'b9907e59a616' -down_revision = '848028ca0487' -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'], ['id']) - op.drop_column('task', 'is_complete') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('task', sa.Column('is_complete', sa.BOOLEAN(), autoincrement=False, nullable=True)) - op.drop_constraint(None, 'task', type_='foreignkey') - op.drop_column('task', 'goal_id') - # ### end Alembic commands ### diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 348eb1cd3..e1f6d1580 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -152,7 +152,7 @@ def test_mark_incomplete_missing_task(client): # Let's add this test for creating tasks, now that # the completion functionality has been implemented # @pytest.mark.skip(reason="No way to test this feature yet") -# def test_create_task_with_valid_completed_at(client): +def test_create_task_with_valid_completed_at(client): # Act response = client.post("/tasks", json={ "title": "A Brand New Task", From 98c7a5452e415207954e5eb28d522058e7a946c9 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 17:31:03 -0500 Subject: [PATCH 10/16] comment out response= --- app/routes.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index 733c9057a..1b1027e2b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -54,11 +54,8 @@ def get_tasks_for_goal(id): for task in goal.tasks: task = validate_task(id) - task_of_goal.append(task.to_dict()) - print(goal_with_tasks, "MY ANS!!!") - return goal_with_tasks @@ -197,11 +194,6 @@ def mark_complete(id): db.session.add(task) db.session.commit() - # print("TASK TITLE **", task.title) - - # task_dict = task.to_dict() - # print("TASK_DICT TITLE", task_dict.title) - slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') @@ -210,7 +202,8 @@ def mark_complete(id): headers = {"Authorization": slack_bot_token} slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' - response = requests.post(slack_url, headers=headers) + ## UNCOMMENT RESPONSE TO POST + #response = requests.post(slack_url, headers=headers) @@ -231,7 +224,7 @@ def mark_incomplete(id): headers = {"Authorization": slack_bot_token} slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' - response = requests.post(slack_url, headers=headers) + # response = requests.post(slack_url, headers=headers) return {"task": task.to_dict()} From 0361a75aa9f359f38b0a8b1477bf01e17603edad Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 17:59:50 -0500 Subject: [PATCH 11/16] add 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 From 65ddc755398b7c0f23d2eddc5d2ba74bd9e3c162 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 19:26:03 -0500 Subject: [PATCH 12/16] add main bp --- app/__init__.py | 4 +++- app/routes.py | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 33c919eef..67fc7e813 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -33,9 +33,11 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - from .routes import task_bp, goal_bp + from .routes import task_bp, goal_bp, main_bp app.register_blueprint(task_bp) app.register_blueprint(goal_bp) + app.register_blueprint(main_bp) + # Register Blueprints here diff --git a/app/routes.py b/app/routes.py index 1b1027e2b..79a84d36b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -12,6 +12,14 @@ task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") goal_bp = Blueprint("goals", __name__, url_prefix="/goals") +main_bp = Blueprint("/", __name__) + +@main_bp.route("", method=["GET"]) +def main_page(): + return ("Welcome to task-list -- A space to track tasks and goals") + + + From e4148b2a491bd1330780d62fe6bce9fcced53d51 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 19:34:29 -0500 Subject: [PATCH 13/16] tried to make route for main page --- app/routes.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 79a84d36b..c8396afda 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,9 +14,9 @@ goal_bp = Blueprint("goals", __name__, url_prefix="/goals") main_bp = Blueprint("/", __name__) -@main_bp.route("", method=["GET"]) -def main_page(): - return ("Welcome to task-list -- A space to track tasks and goals") +# @main_bp.route("", method=["GET"]) +# def main_page(): +# return ("Welcome to task-list -- A space to track tasks and goals") From aafed42ad8c33338b292b70eff808373c0fe1384 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 13 May 2022 19:38:37 -0500 Subject: [PATCH 14/16] comment out --- app/__init__.py | 4 ++-- app/routes.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 67fc7e813..27b9d1f92 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -33,10 +33,10 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - from .routes import task_bp, goal_bp, main_bp + from .routes import task_bp, goal_bp app.register_blueprint(task_bp) app.register_blueprint(goal_bp) - app.register_blueprint(main_bp) + # app.register_blueprint(main_bp) diff --git a/app/routes.py b/app/routes.py index c8396afda..c72b6b711 100644 --- a/app/routes.py +++ b/app/routes.py @@ -12,7 +12,7 @@ task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") goal_bp = Blueprint("goals", __name__, url_prefix="/goals") -main_bp = Blueprint("/", __name__) +# main_bp = Blueprint("/", __name__) # @main_bp.route("", method=["GET"]) # def main_page(): From 48292b606a9009ef2b22024ffa4de84fa53e5ebf Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 1 Jul 2022 01:30:34 -0500 Subject: [PATCH 15/16] added cors --- app/__init__.py | 7 ++++++- app/routes.py | 25 ++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 27b9d1f92..7973f1981 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,6 +4,7 @@ from flask_migrate import Migrate from dotenv import load_dotenv import os +from flask_cors import CORS db = SQLAlchemy() @@ -13,6 +14,10 @@ def create_app(test_config=None): app = Flask(__name__) + CORS(app) + app.config['CORS_HEADERS'] = 'Content-Type' + + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if test_config is None: @@ -41,5 +46,5 @@ def create_app(test_config=None): # Register Blueprints here - + CORS(app) return app diff --git a/app/routes.py b/app/routes.py index c72b6b711..5c7669575 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,11 +20,6 @@ - - - - - @goal_bp.route("", methods=["GET"]) def get_all_goals(): goals = Goal.query.all() @@ -204,11 +199,11 @@ def mark_complete(id): - slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') - channel_name = 'test-channel' - text=f"Someone just completed {task.title}" - headers = {"Authorization": slack_bot_token} - slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' + # slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') + # channel_name = 'test-channel' + # text=f"Someone just completed {task.title}" + # headers = {"Authorization": slack_bot_token} + # slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' ## UNCOMMENT RESPONSE TO POST #response = requests.post(slack_url, headers=headers) @@ -226,11 +221,11 @@ def mark_incomplete(id): db.session.add(task) db.session.commit() - slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') - channel_name = 'test-channel' - text=f"Someone still hasn't completed {task.title}" - headers = {"Authorization": slack_bot_token} - slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' + # slack_bot_token= os.environ.get('SLACK_BOT_TOKEN') + # channel_name = 'test-channel' + # text=f"Someone still hasn't completed {task.title}" + # headers = {"Authorization": slack_bot_token} + # slack_url = f'https://slack.com/api/chat.postMessage?channel={channel_name}&text={text}' # response = requests.post(slack_url, headers=headers) From b4dce2d863a8bb9200941bacac4008573c7a19c3 Mon Sep 17 00:00:00 2001 From: jae Date: Fri, 15 Jul 2022 15:43:05 -0500 Subject: [PATCH 16/16] install cors --- app/__init__.py | 2 +- requirements.txt | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 7973f1981..2878f5af8 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -14,7 +14,7 @@ def create_app(test_config=None): app = Flask(__name__) - CORS(app) + app.config['CORS_HEADERS'] = 'Content-Type' diff --git a/requirements.txt b/requirements.txt index 30ff414fe..8f97165f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,9 +5,17 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +colorama==0.4.5 +cors==1.0.1 +coverage==6.3.2 +filelock==3.7.1 Flask==1.1.2 +Flask-Cors==3.0.10 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +future==0.18.2 +gevent==21.12.0 +greenlet==1.1.2 gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 @@ -21,14 +29,19 @@ psycopg2-binary==2.8.6 py==1.10.0 pycodestyle==2.6.0 pyparsing==2.4.7 +PySocks==1.7.1 pytest==6.2.3 pytest-cov==2.12.1 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 requests==2.25.1 +requests-file==1.5.1 six==1.15.0 SQLAlchemy==1.3.23 +tldextract==3.3.0 toml==0.10.2 urllib3==1.26.5 Werkzeug==1.0.1 +zope.event==4.5.0 +zope.interface==5.4.0