From a5d2d103970df6e15e12044a44fd799081837ff6 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:12:21 -0800 Subject: [PATCH 01/77] Adds Task model --- app/models/task.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..2cf697c62 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,19 @@ from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import String, DateTime +from datetime import datetime +from typing import Optional from ..db import db class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] = mapped_column(String(50)) + description: Mapped[str] = mapped_column(String(255)) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": bool(self.completed_at) + } From 8ad364ab9d93aae5eda7df482776a1a223de6c9f Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:14:03 -0800 Subject: [PATCH 02/77] Adds Task blueprint --- app/__init__.py | 2 ++ app/routes/task_routes.py | 7 ++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..d4a12bd5e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,4 +1,5 @@ from flask import Flask +from .routes.task_routes import bp from .db import db, migrate from .models import task, goal import os @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(bp) return app diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..285cc1752 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,6 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request +from app.models.task import Task +from app.db import db + + +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks/") From 11048e4c655e0c9bacce57ca73df573e6cf10f4f Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:19:11 -0800 Subject: [PATCH 03/77] Updates migration files --- migrations/alembic.ini | 50 ++++++++ migrations/env.py | 113 ++++++++++++++++++ migrations/script.py.mako | 24 ++++ .../versions/330f77104e7e_adds_task_model.py | 39 ++++++ ...23_updates_task_model_description_char_.py | 38 ++++++ 5 files changed, 264 insertions(+) create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/330f77104e7e_adds_task_model.py create mode 100644 migrations/versions/52c8b0992e23_updates_task_model_description_char_.py diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..4c9709271 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# 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', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# 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 get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +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=get_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.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_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/330f77104e7e_adds_task_model.py b/migrations/versions/330f77104e7e_adds_task_model.py new file mode 100644 index 000000000..33a382c7d --- /dev/null +++ b/migrations/versions/330f77104e7e_adds_task_model.py @@ -0,0 +1,39 @@ +"""Adds Task model + +Revision ID: 330f77104e7e +Revises: +Create Date: 2024-10-31 14:38:59.586271 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '330f77104e7e' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(length=50), nullable=False), + sa.Column('description', sa.String(length=50), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/migrations/versions/52c8b0992e23_updates_task_model_description_char_.py b/migrations/versions/52c8b0992e23_updates_task_model_description_char_.py new file mode 100644 index 000000000..29409ec8c --- /dev/null +++ b/migrations/versions/52c8b0992e23_updates_task_model_description_char_.py @@ -0,0 +1,38 @@ +"""Updates Task model - description char restriction + +Revision ID: 52c8b0992e23 +Revises: 330f77104e7e +Create Date: 2024-10-31 14:42:53.966650 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '52c8b0992e23' +down_revision = '330f77104e7e' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.alter_column('description', + existing_type=sa.VARCHAR(length=50), + type_=sa.String(length=255), + existing_nullable=False) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.alter_column('description', + existing_type=sa.String(length=255), + type_=sa.VARCHAR(length=50), + existing_nullable=False) + + # ### end Alembic commands ### From 20dabc8447233f85efafe9a19573f1caf19f6327 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:20:12 -0800 Subject: [PATCH 04/77] Adds create_task to task_routes.py --- app/routes/task_routes.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 285cc1752..e15086e67 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -4,3 +4,21 @@ bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks/") + +@bp.post("") +def create_task(): + req_body = request.get_json() + title = req_body["title"] + description = req_body["description"] + completed_at = req_body.get("completed_at", None) + + new_task = Task( + title=title, + description=description, + completed_at=completed_at, + ) + + db.session.add(new_task) + db.session.commit() + + return {"task": new_task.to_dict()}, 201 From af1072555335e36d105a186fd933f24d7b311651 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:58:05 -0800 Subject: [PATCH 05/77] Adds get_one_task function --- app/routes/task_routes.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e15086e67..80e66ef7d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -22,3 +22,13 @@ def create_task(): db.session.commit() return {"task": new_task.to_dict()}, 201 +@bp.get("/") +def get_one_task(task_id): + try: + task_id = int(task_id) + except ValueError: + return {} + query = db.select(Task).where(Task.id == task_id) + task = db.session.scalar(query) + + return { "task": task.to_dict() }, 200 From 1a41d6073f757f3db52cd7c40bda99197495fe87 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 14:58:27 -0800 Subject: [PATCH 06/77] Adds get_all_tasks function --- app/routes/task_routes.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 80e66ef7d..807896154 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -23,6 +23,27 @@ def create_task(): return {"task": new_task.to_dict()}, 201 @bp.get("/") +@bp.get("/", strict_slashes=False) +def get_all_tasks(): + query = db.select(Task).order_by(Task.id) + + for attribute, value in request.args.items(): + if hasattr(Task, attribute): + query = query.where(getattr(Task, attribute).ilike(f"%{value}%")) + + tasks = db.session.scalars(query) + return [task.to_dict() for task in tasks], 200 + +@bp.get("/") +def get_one_task(task_id): + try: + task_id = int(task_id) + except ValueError: + return {} + query = db.select(Task).where(Task.id == task_id) + task = db.session.scalar(query) + + return { "task": task.to_dict() }, 200 def get_one_task(task_id): try: task_id = int(task_id) From 4d17fc65f6b1e8374d27fab4cb70166f23854398 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 15:20:45 -0800 Subject: [PATCH 07/77] refactor: Adds Task class method from_dict --- app/models/task.py | 10 ++++++++++ app/routes/task_routes.py | 28 ++++++---------------------- tests/test_wave_01.py | 31 +++++++++++++++++-------------- 3 files changed, 33 insertions(+), 36 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 2cf697c62..6a917f91e 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -17,3 +17,13 @@ def to_dict(self): "description": self.description, "is_complete": bool(self.completed_at) } + + @classmethod + def from_dict(cls, data): + task = Task( + title=data["title"], + description=data["description"], + completed_at=data["completed_at"], + ) + + return task diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 807896154..018f8c21d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,26 +3,19 @@ from app.db import db -bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks/") +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") -@bp.post("") +@bp.post("/", strict_slashes=False) def create_task(): req_body = request.get_json() - title = req_body["title"] - description = req_body["description"] - completed_at = req_body.get("completed_at", None) - - new_task = Task( - title=title, - description=description, - completed_at=completed_at, - ) + req_body["completed_at"] = req_body.get("completed_at", None) + new_task = Task.from_dict(req_body) db.session.add(new_task) db.session.commit() return {"task": new_task.to_dict()}, 201 -@bp.get("/") + @bp.get("/", strict_slashes=False) def get_all_tasks(): query = db.select(Task).order_by(Task.id) @@ -34,16 +27,7 @@ def get_all_tasks(): tasks = db.session.scalars(query) return [task.to_dict() for task in tasks], 200 -@bp.get("/") -def get_one_task(task_id): - try: - task_id = int(task_id) - except ValueError: - return {} - query = db.select(Task).where(Task.id == task_id) - task = db.session.scalar(query) - - return { "task": task.to_dict() }, 200 +@bp.get("/", strict_slashes=False) def get_one_task(task_id): try: task_id = int(task_id) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..f24bbf44b 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") @@ -66,7 +66,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={ @@ -74,6 +74,7 @@ def test_create_task(client): "description": "Test Description", }) response_body = response.get_json() + print("response_body: ", response_body) # Assert assert response.status_code == 201 @@ -87,13 +88,15 @@ def test_create_task(client): } } new_task = Task.query.get(1) - assert new_task - assert new_task.title == "A Brand New Task" - assert new_task.description == "Test Description" - assert new_task.completed_at == None + print(new_task) + print(Task.query) + # assert new_task + # assert new_task.title == "A Brand New Task" + # assert new_task.description == "Test Description" + # assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -119,7 +122,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={ @@ -137,7 +140,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") @@ -152,7 +155,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") @@ -169,7 +172,7 @@ def test_delete_task_not_found(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -186,7 +189,7 @@ def test_create_task_must_contain_title(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ From a6094b64abe088b5d13c1b63a2644df651a6884c Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 16:20:58 -0800 Subject: [PATCH 08/77] Adds edit_task function --- app/models/task.py | 4 +++- app/routes/task_routes.py | 31 ++++++++++++++++++++++++++++--- tests/test_wave_01.py | 16 +++++----------- 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 6a917f91e..a95381096 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -17,9 +17,11 @@ def to_dict(self): "description": self.description, "is_complete": bool(self.completed_at) } - + @classmethod def from_dict(cls, data): + data["completed_at"] = data.get("completed_at", None) + task = Task( title=data["title"], description=data["description"], diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 018f8c21d..4248fd498 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, request +from flask import Blueprint, request, make_response, abort, Response from app.models.task import Task from app.db import db @@ -8,7 +8,6 @@ @bp.post("/", strict_slashes=False) def create_task(): req_body = request.get_json() - req_body["completed_at"] = req_body.get("completed_at", None) new_task = Task.from_dict(req_body) db.session.add(new_task) @@ -29,11 +28,37 @@ def get_all_tasks(): @bp.get("/", strict_slashes=False) def get_one_task(task_id): + task = validate_task(task_id) + + return { "task": task.to_dict() }, 200 + +def validate_task(task_id): try: task_id = int(task_id) except ValueError: - return {} + message = { "message": f"Task ID {task_id} is invalid"} + abort(make_response(message, 400)) + query = db.select(Task).where(Task.id == task_id) task = db.session.scalar(query) + if not task: + message = {"message": f"Task with ID {task_id} was not found"} + abort(make_response(message, 404)) + + return task + +@bp.put("/", strict_slashes=False) +def update_task(task_id): + req_body = request.get_json() + req_body["completed_at"] = req_body.get("completed_at", None) + task = validate_task(task_id) + + task.title = req_body["title"] + task.description = req_body["description"] + task.completed_at = req_body["completed_at"] + + db.session.commit() + + print({ "task": task.to_dict() }) return { "task": task.to_dict() }, 200 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index f24bbf44b..06c754668 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -88,12 +88,10 @@ def test_create_task(client): } } new_task = Task.query.get(1) - print(new_task) - print(Task.query) - # assert new_task - # assert new_task.title == "A Brand New Task" - # assert new_task.description == "Test Description" - # assert new_task.completed_at == None + assert new_task + assert new_task.title == "A Brand New Task" + assert new_task.description == "Test Description" + assert new_task.completed_at == None # @pytest.mark.skip(reason="No way to test this feature yet") @@ -133,11 +131,7 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response.get_json() == {"message": "Task with ID 1 was not found"} # @pytest.mark.skip(reason="No way to test this feature yet") From 7d877be72f8de904ef0921bb53bd78212f40ec30 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 17:59:10 -0800 Subject: [PATCH 09/77] Adds delete_task function --- app/routes/task_routes.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 4248fd498..5315d7173 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -8,6 +8,9 @@ @bp.post("/", strict_slashes=False) def create_task(): req_body = request.get_json() + if "title" not in req_body or "description" not in req_body: + message = {"details": "Invalid data"} + abort(make_response(message, 400)) new_task = Task.from_dict(req_body) db.session.add(new_task) @@ -62,3 +65,11 @@ def update_task(task_id): print({ "task": task.to_dict() }) return { "task": task.to_dict() }, 200 + +@bp.delete("/", strict_slashes=False) +def delete_task(task_id): + task = validate_task(task_id) + db.session.delete(task) + db.session.commit() + + return {"details": f'Task {task.id} "{task.title}" successfully deleted'}, 200 From 991f8602689761bf0c5ba61eb823063c450c97c7 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 17:59:38 -0800 Subject: [PATCH 10/77] Fixes tests for wave 1 --- tests/test_wave_01.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 06c754668..0ef13143e 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -51,7 +51,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -59,11 +59,8 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response.get_json() == {"message": "Task with ID 1 was not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** # @pytest.mark.skip(reason="No way to test this feature yet") @@ -157,11 +154,8 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert response.get_json() == {"message": "Task with ID 1 was not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** assert Task.query.all() == [] From 055a22feb2819858a77b061f0768feb41f86bfca Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 18:46:59 -0800 Subject: [PATCH 11/77] Adds sorting order to get_all_tasks --- app/routes/task_routes.py | 4 +++- tests/test_wave_02.py | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 5315d7173..8ef33fe5f 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -20,7 +20,9 @@ def create_task(): @bp.get("/", strict_slashes=False) def get_all_tasks(): - query = db.select(Task).order_by(Task.id) + + sort = request.args.get("sort") + query = db.select(Task).order_by(Task.title.desc() if sort=="desc" else Task.title) for attribute, value in request.args.items(): if hasattr(Task, attribute): diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..651e3aebd 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") From 28589438a42be12bacc02ff23c1debe53e4b5982 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 5 Nov 2024 19:26:32 -0800 Subject: [PATCH 12/77] Adds complete and incomplete tasks finctionality --- app/routes/task_routes.py | 19 ++++++++++++++++++- tests/test_wave_03.py | 23 ++++++++--------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 8ef33fe5f..9f3c82930 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint, request, make_response, abort, Response +from flask import Blueprint, request, make_response, abort +from datetime import datetime from app.models.task import Task from app.db import db @@ -75,3 +76,19 @@ def delete_task(task_id): db.session.commit() return {"details": f'Task {task.id} "{task.title}" successfully deleted'}, 200 + +@bp.patch("//mark_complete") +def mark_task_completed(task_id): + task = validate_task(task_id) + task.completed_at = datetime.now() + db.session.commit() + + return { "task": task.to_dict() }, 200 + +@bp.patch("//mark_incomplete") +def mark_task_incompleted(task_id): + task = validate_task(task_id) + task.completed_at = None + db.session.commit() + + return { "task": task.to_dict() }, 200 \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..a27b98f1a 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -42,7 +42,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -62,7 +62,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +99,7 @@ def test_mark_complete_on_completed_task(client, completed_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -119,7 +119,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -127,14 +127,10 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response.get_json() == { "message": "Task with ID 1 was not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +138,5 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response.get_json() == { "message": "Task with ID 1 was not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** From 3c6bb1f44b6acb93b6cd1135a0905f75cf2d2da3 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 13:21:01 -0800 Subject: [PATCH 13/77] Adds message sending functionality to mark_task_completed --- .gitignore | 5 ++++- app/routes/task_routes.py | 27 +++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 4e9b18359..f629beed5 100644 --- a/.gitignore +++ b/.gitignore @@ -138,4 +138,7 @@ dmypy.json .pytype/ # Cython debug symbols -cython_debug/ \ No newline at end of file +cython_debug/ + +# Slack bot logo +slack_bot_logo.png \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 9f3c82930..64d738f56 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,9 @@ from flask import Blueprint, request, make_response, abort from datetime import datetime +import requests from app.models.task import Task from app.db import db +from os import environ bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @@ -82,7 +84,12 @@ def mark_task_completed(task_id): task = validate_task(task_id) task.completed_at = datetime.now() db.session.commit() - + message_is_sent = send_task_complete_message(task.title) + print(message_is_sent) + if not message_is_sent: + raise Exception( + "An error occured during notification sending!\ + Please connect to the Task List developer!") return { "task": task.to_dict() }, 200 @bp.patch("//mark_incomplete") @@ -91,4 +98,20 @@ def mark_task_incompleted(task_id): task.completed_at = None db.session.commit() - return { "task": task.to_dict() }, 200 \ No newline at end of file + return { "task": task.to_dict() }, 200 + +def send_task_complete_message(task_title): + request_data = { + # "channel": "#api-test-channel", # Slack channel for tests + "channel": "U07GC9C8Y4X", # My Slack account ID + "username": "Task List app", + "text": f"Someone just completed the task \"{task_title}\"" + } + message_status = requests.post( + url="https://slack.com/api/chat.postMessage", + json=request_data, + headers={"Authorization": environ.get('SLACK_API_KEY')}, + timeout=1 + ) + + return message_status.json()["ok"] From ededb6762d773a4288723a389ee8a5d024a9772d Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 13:21:56 -0800 Subject: [PATCH 14/77] Creates Goal model --- app/models/goal.py | 8 +++++ .../3edabf27ff58_adds_updates_goal_model.py | 32 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 migrations/versions/3edabf27ff58_adds_updates_goal_model.py diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..b444fcd06 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,13 @@ from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import String from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] = mapped_column(String(50)) + + def to_dict(self): + return { + "id": self.id, + "title": self.title + } diff --git a/migrations/versions/3edabf27ff58_adds_updates_goal_model.py b/migrations/versions/3edabf27ff58_adds_updates_goal_model.py new file mode 100644 index 000000000..719266c02 --- /dev/null +++ b/migrations/versions/3edabf27ff58_adds_updates_goal_model.py @@ -0,0 +1,32 @@ +"""Adds updates Goal model + +Revision ID: 3edabf27ff58 +Revises: 52c8b0992e23 +Create Date: 2024-11-07 13:16:55.721590 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '3edabf27ff58' +down_revision = '52c8b0992e23' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.add_column(sa.Column('title', sa.String(length=50), nullable=False)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### From 4bdfaec21d60dd431c45324fc45d806282087f8d Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 14:29:33 -0800 Subject: [PATCH 15/77] refactor: Creates validate_model and set_new_attributes route utilities --- app/routes/route_utilities.py | 28 +++++++++++++++++++++ app/routes/task_routes.py | 46 +++++++++++------------------------ 2 files changed, 42 insertions(+), 32 deletions(-) create mode 100644 app/routes/route_utilities.py diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..3b91d6260 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,28 @@ +from flask import abort, make_response +from app.db import db + +def apply_filters(cls, arguments, query): + for attribute, value in arguments: + if hasattr(cls, attribute): + query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) + +def validate_model(cls, cls_id): + try: + cls_id = int(cls_id) + except ValueError: + message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} + abort(make_response(message, 400)) + + query = db.select(cls).where(cls.id == cls_id) + result = db.session.scalar(query) + + if not result: + message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} + abort(make_response(message, 404)) + + return result + +def set_new_attributes(instance, req_body): + for attr, value in req_body.items(): + if hasattr(instance, attr): + setattr(instance, attr, value) \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 64d738f56..b8acd1c01 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,10 +1,11 @@ from flask import Blueprint, request, make_response, abort from datetime import datetime +from os import environ import requests + from app.models.task import Task from app.db import db -from os import environ - +from app.routes.route_utilities import apply_filters, validate_model, set_new_attributes bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @@ -27,53 +28,33 @@ def get_all_tasks(): sort = request.args.get("sort") query = db.select(Task).order_by(Task.title.desc() if sort=="desc" else Task.title) - for attribute, value in request.args.items(): - if hasattr(Task, attribute): - query = query.where(getattr(Task, attribute).ilike(f"%{value}%")) + apply_filters(Task, request.args.items(), query) tasks = db.session.scalars(query) return [task.to_dict() for task in tasks], 200 @bp.get("/", strict_slashes=False) def get_one_task(task_id): - task = validate_task(task_id) - - return { "task": task.to_dict() }, 200 + task = validate_model(Task, task_id) -def validate_task(task_id): - try: - task_id = int(task_id) - except ValueError: - message = { "message": f"Task ID {task_id} is invalid"} - abort(make_response(message, 400)) - - query = db.select(Task).where(Task.id == task_id) - task = db.session.scalar(query) - - if not task: - message = {"message": f"Task with ID {task_id} was not found"} - abort(make_response(message, 404)) + return { "task": task.to_dict() if task else task}, 200 - return task @bp.put("/", strict_slashes=False) def update_task(task_id): req_body = request.get_json() req_body["completed_at"] = req_body.get("completed_at", None) - task = validate_task(task_id) + task = validate_model(Task, task_id) - task.title = req_body["title"] - task.description = req_body["description"] - task.completed_at = req_body["completed_at"] + set_new_attributes(task, req_body) + print(*task.to_dict(), sep='\n') db.session.commit() - - print({ "task": task.to_dict() }) return { "task": task.to_dict() }, 200 @bp.delete("/", strict_slashes=False) def delete_task(task_id): - task = validate_task(task_id) + task = validate_model(Task, task_id) db.session.delete(task) db.session.commit() @@ -81,11 +62,12 @@ def delete_task(task_id): @bp.patch("//mark_complete") def mark_task_completed(task_id): - task = validate_task(task_id) + task = validate_model(Task, task_id) task.completed_at = datetime.now() db.session.commit() + message_is_sent = send_task_complete_message(task.title) - print(message_is_sent) + if not message_is_sent: raise Exception( "An error occured during notification sending!\ @@ -94,7 +76,7 @@ def mark_task_completed(task_id): @bp.patch("//mark_incomplete") def mark_task_incompleted(task_id): - task = validate_task(task_id) + task = validate_model(Task, task_id) task.completed_at = None db.session.commit() From 0589dab294207e552ae82267f5b509fcd7fbcf99 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 14:29:56 -0800 Subject: [PATCH 16/77] feat: Creates goal routes --- app/__init__.py | 6 ++-- app/routes/goal_routes.py | 60 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index d4a12bd5e..a3fd2bd59 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,5 +1,6 @@ from flask import Flask -from .routes.task_routes import bp +from .routes.task_routes import bp as task_bp +from .routes.goal_routes import bp as goal_bp from .db import db, migrate from .models import task, goal import os @@ -19,6 +20,7 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here - app.register_blueprint(bp) + app.register_blueprint(task_bp) + app.register_blueprint(goal_bp) return app diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..b9776384c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,59 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, abort, make_response +from app.models.goal import Goal +from app.db import db +from app.routes.route_utilities import apply_filters, validate_model, set_new_attributes + +bp = Blueprint("goal_bp", __name__, url_prefix="/goals") + + +@bp.post("/", strict_slashes=False) +def create_goal(): + req_body = request.get_json() + if "title" not in req_body: + message = {"details": "Invalid data"} + abort(make_response(message, 400)) + + new_goal = Goal(req_body["title"]) + + db.session.add(new_goal) + db.session.commit() + + return {"goal": new_goal.to_dict()}, 201 + + +@bp.get("/", strict_slashes=False) +def get_all_goals(): + sort = request.args.get("sort") + query = db.select(Goal).order_by(Goal.title.desc() if sort=="desc" else Goal.title) + + apply_filters(Goal, request.args.items(), query) + + goals = db.session.scalars(query) + return [goal.to_dict() for goal in goals], 200 + + +@bp.get("/", strict_slashes=False) +def get_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return { "goal": goal.to_dict() }, 200 + + +@bp.put("/", strict_slashes=False) +def update_goal(goal_id): + req_body = request.get_json() + goal = validate_model(Goal, goal_id) + set_new_attributes(Goal, req_body) + + db.session.commit() + + return { "goal": goal.to_dict() }, 200 + + +@bp.delete("/", strict_slashes=False) +def delete_goal(goal_id): + goal = validate_model(Goal, goal_id) + db.session.delete(goal) + db.session.commit() + + return {"details": f'goal {goal.id} "{goal.title}" successfully deleted'}, 200 From 360a353d1af082e3ffdec533a251df7b11516c79 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 15:13:24 -0800 Subject: [PATCH 17/77] Adds tests for goal_routes functions --- app/models/goal.py | 7 ++++ app/routes/goal_routes.py | 4 +- app/routes/route_utilities.py | 2 +- tests/test_wave_05.py | 72 +++++++++++++++-------------------- 4 files changed, 40 insertions(+), 45 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index b444fcd06..421f9b3e7 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -6,6 +6,13 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] = mapped_column(String(50)) + # The __init__ method is defined instead of a from_dict class method. + # Since this model only requires one parameter, from_dict isn't necessary. + # By defining __init__, the constructor becomes more flexible, allowing + # both positional and keyword arguments for instantiation. + def __init__(self, title) -> None: + self.title = title + def to_dict(self): return { "id": self.id, diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index b9776384c..f396a3242 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -43,7 +43,7 @@ def get_one_goal(goal_id): def update_goal(goal_id): req_body = request.get_json() goal = validate_model(Goal, goal_id) - set_new_attributes(Goal, req_body) + set_new_attributes(goal, req_body) db.session.commit() @@ -56,4 +56,4 @@ def delete_goal(goal_id): db.session.delete(goal) db.session.commit() - return {"details": f'goal {goal.id} "{goal.title}" successfully deleted'}, 200 + return {"details": f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200 diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 3b91d6260..47f2f98cc 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -25,4 +25,4 @@ def validate_model(cls, cls_id): def set_new_attributes(instance, req_body): for attr, value in req_body.items(): if hasattr(instance, attr): - setattr(instance, attr, value) \ No newline at end of file + setattr(instance, attr, value) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..b996d86b9 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,4 @@ -import pytest - - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +9,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -29,7 +26,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +43,19 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal with ID 1 was not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,34 +74,33 @@ 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 ---- + request = client.put("/goals/1", json={ + "title": "Become a software developer!" + }) + request_body = request.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert request.status_code == 200 + assert request_body == { "goal": {"id": 1, "title": "Become a software developer!"}} -@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") # Act - # ---- Complete Act Here ---- + request = client.put("/goals/1", json={ + "title": "Become a software developer!" + }) + request_body = request.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert request.status_code == 404 + assert request_body == {"message": "Goal with ID 1 was not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -123,28 +116,23 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 + assert response.get_json() == {"message": "Goal with ID 1 was not found"} - 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.get_json() == {"message": "Goal with ID 1 was not found"} + -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) From 23f70c11b6bcaa6a174ab3e22d0b4520f7a0a23e Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 7 Nov 2024 23:11:20 -0800 Subject: [PATCH 18/77] Adds /tasks GET and POST routes to Blueprint Goal --- app/models/goal.py | 3 +- app/models/task.py | 13 +++++-- app/routes/goal_routes.py | 34 +++++++++++++++++++ ...a75ee36d48f_adds_goal_task_relationship.py | 34 +++++++++++++++++++ tests/test_wave_06.py | 18 ++++------ 5 files changed, 87 insertions(+), 15 deletions(-) create mode 100644 migrations/versions/ea75ee36d48f_adds_goal_task_relationship.py diff --git a/app/models/goal.py b/app/models/goal.py index 421f9b3e7..b88ccb710 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,10 +1,11 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from sqlalchemy import String from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] = mapped_column(String(50)) + tasks: Mapped[list["Task"]] = relationship(back_populates="goal") # The __init__ method is defined instead of a from_dict class method. # Since this model only requires one parameter, from_dict isn't necessary. diff --git a/app/models/task.py b/app/models/task.py index a95381096..ca81de70f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,5 @@ -from sqlalchemy.orm import Mapped, mapped_column -from sqlalchemy import String, DateTime +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import String, DateTime, ForeignKey from datetime import datetime from typing import Optional from ..db import db @@ -9,15 +9,22 @@ class Task(db.Model): title: Mapped[str] = mapped_column(String(50)) description: Mapped[str] = mapped_column(String(255)) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") def to_dict(self): - return { + task_dict = { "id": self.id, "title": self.title, "description": self.description, "is_complete": bool(self.completed_at) } + if self.goal_id is not None: + task_dict["goal_id"] = self.goal_id + + return task_dict + @classmethod def from_dict(cls, data): data["completed_at"] = data.get("completed_at", None) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index f396a3242..3f3f2020f 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, request, abort, make_response from app.models.goal import Goal +from app.models.task import Task from app.db import db from app.routes.route_utilities import apply_filters, validate_model, set_new_attributes @@ -57,3 +58,36 @@ def delete_goal(goal_id): db.session.commit() return {"details": f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200 + +@bp.post("//tasks") +def assign_task_to_goal(goal_id): + goal = validate_model(Goal, goal_id) + task_ids = request.get_json().get("task_ids", []) + print("##### task_ids", task_ids, type(task_ids)) + list_of_tasks = [] + + for task_id in task_ids: + task = validate_model(Task, task_id) + print(">>>>", task.to_dict()) + if task: + list_of_tasks.append(task) + + print("$$$$", goal.tasks) + print("$$$$", [task.id for task in goal.tasks]) + goal.tasks.extend(list_of_tasks) + db.session.commit() + + return { + "id": goal.id, + "task_ids": [task.id for task in goal.tasks] + } + +@bp.get("//tasks") +def get_task_of_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return { + "id": goal.id, + "title": goal.title, + "tasks": [task.to_dict() for task in goal.tasks] + } diff --git a/migrations/versions/ea75ee36d48f_adds_goal_task_relationship.py b/migrations/versions/ea75ee36d48f_adds_goal_task_relationship.py new file mode 100644 index 000000000..710a8aafd --- /dev/null +++ b/migrations/versions/ea75ee36d48f_adds_goal_task_relationship.py @@ -0,0 +1,34 @@ +"""Adds goal-task relationship + +Revision ID: ea75ee36d48f +Revises: 3edabf27ff58 +Create Date: 2024-11-07 22:06:33.461758 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'ea75ee36d48f' +down_revision = '3edabf27ff58' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..b83267a86 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -23,7 +23,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(Goal.query.get(1).tasks) == 3 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -42,7 +42,7 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on assert len(Goal.query.get(1).tasks) == 2 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act response = client.get("/goals/1/tasks") @@ -50,14 +50,10 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert response_body == {'message': 'Goal with ID 1 was not found'} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -74,7 +70,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 +95,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 b4031cc91e2aafa3c92b7fff0cb6e09ff2e31e8e Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Fri, 8 Nov 2024 10:06:52 -0800 Subject: [PATCH 19/77] refactor: removes abondend nullable --- app/models/task.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/task.py b/app/models/task.py index ca81de70f..123272b6a 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,7 +8,7 @@ class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] = mapped_column(String(50)) description: Mapped[str] = mapped_column(String(255)) - completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime) goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") From d96de8b4210fd3e992016981336ecc31542e78fb Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 15:52:32 -0800 Subject: [PATCH 20/77] refactor: minor changes --- app/routes/task_routes.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index b8acd1c01..74facbdab 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -42,12 +42,11 @@ def get_one_task(task_id): @bp.put("/", strict_slashes=False) def update_task(task_id): + task = validate_model(Task, task_id) req_body = request.get_json() req_body["completed_at"] = req_body.get("completed_at", None) - task = validate_model(Task, task_id) set_new_attributes(task, req_body) - print(*task.to_dict(), sep='\n') db.session.commit() return { "task": task.to_dict() }, 200 @@ -92,7 +91,10 @@ def send_task_complete_message(task_title): message_status = requests.post( url="https://slack.com/api/chat.postMessage", json=request_data, - headers={"Authorization": environ.get('SLACK_API_KEY')}, + headers={ + "Authorization": environ.get('SLACK_API_KEY'), + "Content Type": "application/json" + }, timeout=1 ) From 81eb79061a475374a44fa47cba02374508a61c89 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:18:13 -0800 Subject: [PATCH 21/77] refactor: Creates utility func create_class_instance --- app/models/goal.py | 12 +++++------- app/routes/goal_routes.py | 14 ++------------ app/routes/route_utilities.py | 12 ++++++++++++ app/routes/task_routes.py | 14 +++----------- 4 files changed, 22 insertions(+), 30 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index b88ccb710..68a49b7e3 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -7,15 +7,13 @@ class Goal(db.Model): title: Mapped[str] = mapped_column(String(50)) tasks: Mapped[list["Task"]] = relationship(back_populates="goal") - # The __init__ method is defined instead of a from_dict class method. - # Since this model only requires one parameter, from_dict isn't necessary. - # By defining __init__, the constructor becomes more flexible, allowing - # both positional and keyword arguments for instantiation. - def __init__(self, title) -> None: - self.title = title - def to_dict(self): return { "id": self.id, "title": self.title } + + @classmethod + def from_dict(cls, data): + return Goal(title=data["title"]) + diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3f3f2020f..89ea8aca3 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,24 +2,14 @@ from app.models.goal import Goal from app.models.task import Task from app.db import db -from app.routes.route_utilities import apply_filters, validate_model, set_new_attributes +from app.routes.route_utilities import * bp = Blueprint("goal_bp", __name__, url_prefix="/goals") @bp.post("/", strict_slashes=False) def create_goal(): - req_body = request.get_json() - if "title" not in req_body: - message = {"details": "Invalid data"} - abort(make_response(message, 400)) - - new_goal = Goal(req_body["title"]) - - db.session.add(new_goal) - db.session.commit() - - return {"goal": new_goal.to_dict()}, 201 + return create_class_instance(Goal, request, ["title"]) @bp.get("/", strict_slashes=False) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 47f2f98cc..44e8affc3 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -26,3 +26,15 @@ def set_new_attributes(instance, req_body): for attr, value in req_body.items(): if hasattr(instance, attr): setattr(instance, attr, value) + +def create_class_instance(cls, request, required_fields): + req_body = request.get_json() + for param in required_fields: + if param not in req_body: + message = {"details": "Invalid data"} + abort(make_response(message, 400)) + new_instance = cls.from_dict(req_body) + db.session.add(new_instance) + db.session.commit() + + return {cls.__name__.lower(): new_instance.to_dict()}, 201 \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 74facbdab..878b45c51 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -5,25 +5,17 @@ from app.models.task import Task from app.db import db -from app.routes.route_utilities import apply_filters, validate_model, set_new_attributes +from app.routes.route_utilities import * bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") @bp.post("/", strict_slashes=False) def create_task(): - req_body = request.get_json() - if "title" not in req_body or "description" not in req_body: - message = {"details": "Invalid data"} - abort(make_response(message, 400)) - new_task = Task.from_dict(req_body) - - db.session.add(new_task) - db.session.commit() - - return {"task": new_task.to_dict()}, 201 + return create_class_instance(Task, request, ["title", "description"]) @bp.get("/", strict_slashes=False) def get_all_tasks(): + print("MEMBERS: ", Task.__annotations__.keys()) sort = request.args.get("sort") query = db.select(Task).order_by(Task.title.desc() if sort=="desc" else Task.title) From e328024430ef4f7507b2e30cb8e74610830db815 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:38:10 -0800 Subject: [PATCH 22/77] refactor: Creates utility func get_all_instances --- app/routes/goal_routes.py | 9 +-------- app/routes/route_utilities.py | 12 +++++++++++- app/routes/task_routes.py | 10 +--------- 3 files changed, 13 insertions(+), 18 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 89ea8aca3..0112a5f03 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -14,14 +14,7 @@ def create_goal(): @bp.get("/", strict_slashes=False) def get_all_goals(): - sort = request.args.get("sort") - query = db.select(Goal).order_by(Goal.title.desc() if sort=="desc" else Goal.title) - - apply_filters(Goal, request.args.items(), query) - - goals = db.session.scalars(query) - return [goal.to_dict() for goal in goals], 200 - + return get_all_instances(Goal, request.args) @bp.get("/", strict_slashes=False) def get_one_goal(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 44e8affc3..c3944cbb9 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -37,4 +37,14 @@ def create_class_instance(cls, request, required_fields): db.session.add(new_instance) db.session.commit() - return {cls.__name__.lower(): new_instance.to_dict()}, 201 \ No newline at end of file + return {cls.__name__.lower(): new_instance.to_dict()}, 201 + +def get_all_instances(cls, args): + sort = args.get("sort") + query = db.select(cls).order_by(cls.title.desc() if sort=="desc" else cls.title) + + apply_filters(cls, args.items(), query) + + instances = db.session.scalars(query) + return [instance.to_dict() for instance in instances], 200 + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 878b45c51..eff48147e 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -15,15 +15,7 @@ def create_task(): @bp.get("/", strict_slashes=False) def get_all_tasks(): - print("MEMBERS: ", Task.__annotations__.keys()) - - sort = request.args.get("sort") - query = db.select(Task).order_by(Task.title.desc() if sort=="desc" else Task.title) - - apply_filters(Task, request.args.items(), query) - - tasks = db.session.scalars(query) - return [task.to_dict() for task in tasks], 200 + return get_all_instances(Task, request.args) @bp.get("/", strict_slashes=False) def get_one_task(task_id): From d2fbaf47fad11a8d5a4be175d7e2269a4b7bf5f8 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:39:17 -0800 Subject: [PATCH 23/77] refactor: Creates utility func get_one_instance --- app/routes/goal_routes.py | 5 +---- app/routes/route_utilities.py | 5 +++++ app/routes/task_routes.py | 5 +---- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 0112a5f03..9d4409fa5 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -18,10 +18,7 @@ def get_all_goals(): @bp.get("/", strict_slashes=False) def get_one_goal(goal_id): - goal = validate_model(Goal, goal_id) - - return { "goal": goal.to_dict() }, 200 - + return get_one_instance(Goal, goal_id) @bp.put("/", strict_slashes=False) def update_goal(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index c3944cbb9..ea5285cc2 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -48,3 +48,8 @@ def get_all_instances(cls, args): instances = db.session.scalars(query) return [instance.to_dict() for instance in instances], 200 +def get_one_instance(cls, instance_id): + instance = validate_model(cls, instance_id) + + return { cls.__name__.lower(): instance.to_dict() if instance else instance}, 200 + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index eff48147e..d4941da3a 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -19,10 +19,7 @@ def get_all_tasks(): @bp.get("/", strict_slashes=False) def get_one_task(task_id): - task = validate_model(Task, task_id) - - return { "task": task.to_dict() if task else task}, 200 - + return get_one_instance(Task, task_id) @bp.put("/", strict_slashes=False) def update_task(task_id): From db350a8dbded685f14e20c38149a0b4de6065655 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:39:53 -0800 Subject: [PATCH 24/77] refactor: Creates utility func update_instance --- app/routes/goal_routes.py | 9 +-------- app/routes/route_utilities.py | 10 ++++++++++ app/routes/task_routes.py | 9 +-------- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 9d4409fa5..e5f70aa99 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -22,14 +22,7 @@ def get_one_goal(goal_id): @bp.put("/", strict_slashes=False) def update_goal(goal_id): - req_body = request.get_json() - goal = validate_model(Goal, goal_id) - set_new_attributes(goal, req_body) - - db.session.commit() - - return { "goal": goal.to_dict() }, 200 - + return update_instance(Goal, goal_id, request) @bp.delete("/", strict_slashes=False) def delete_goal(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index ea5285cc2..f5adcbddf 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -53,3 +53,13 @@ def get_one_instance(cls, instance_id): return { cls.__name__.lower(): instance.to_dict() if instance else instance}, 200 +def update_instance(cls, instance_id, request): + instance = validate_model(cls, instance_id) + req_body = request.get_json() + if cls.__name__ == "Task": + req_body["completed_at"] = req_body.get("completed_at", None) + + set_new_attributes(instance, req_body) + + db.session.commit() + return { cls.__name__.lower(): instance.to_dict() }, 200 \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d4941da3a..0d3679f68 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -23,14 +23,7 @@ def get_one_task(task_id): @bp.put("/", strict_slashes=False) def update_task(task_id): - task = validate_model(Task, task_id) - req_body = request.get_json() - req_body["completed_at"] = req_body.get("completed_at", None) - - set_new_attributes(task, req_body) - - db.session.commit() - return { "task": task.to_dict() }, 200 + return update_instance(Task, task_id, request) @bp.delete("/", strict_slashes=False) def delete_task(task_id): From b4c37a8c8b81a81770cb7cbcb055eafeb765b25a Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:44:00 -0800 Subject: [PATCH 25/77] refactor: Creates utility func delete_instance --- app/routes/goal_routes.py | 7 +------ app/routes/route_utilities.py | 9 ++++++++- app/routes/task_routes.py | 6 +----- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index e5f70aa99..2259605a2 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -11,7 +11,6 @@ def create_goal(): return create_class_instance(Goal, request, ["title"]) - @bp.get("/", strict_slashes=False) def get_all_goals(): return get_all_instances(Goal, request.args) @@ -26,11 +25,7 @@ def update_goal(goal_id): @bp.delete("/", strict_slashes=False) def delete_goal(goal_id): - goal = validate_model(Goal, goal_id) - db.session.delete(goal) - db.session.commit() - - return {"details": f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200 + return delete_instance(Goal, goal_id) @bp.post("//tasks") def assign_task_to_goal(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index f5adcbddf..f45b4293c 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -62,4 +62,11 @@ def update_instance(cls, instance_id, request): set_new_attributes(instance, req_body) db.session.commit() - return { cls.__name__.lower(): instance.to_dict() }, 200 \ No newline at end of file + return { cls.__name__.lower(): instance.to_dict() }, 200 + +def delete_instance(cls, instance_id): + instance = validate_model(cls, instance_id) + db.session.delete(instance) + db.session.commit() + + return {"details": f'{cls.__name__} {instance.id} "{instance.title}" successfully deleted'}, 200 \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 0d3679f68..44dabe291 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -27,11 +27,7 @@ def update_task(task_id): @bp.delete("/", strict_slashes=False) def delete_task(task_id): - task = validate_model(Task, task_id) - db.session.delete(task) - db.session.commit() - - return {"details": f'Task {task.id} "{task.title}" successfully deleted'}, 200 + return delete_instance(Task, task_id) @bp.patch("//mark_complete") def mark_task_completed(task_id): From a8c75bb4bc03d776ee2d8e3eb1475da24c3ae4c5 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 20:45:56 -0800 Subject: [PATCH 26/77] chore: remove print statements --- app/routes/goal_routes.py | 6 +----- app/routes/task_routes.py | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 2259605a2..681117b39 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -31,17 +31,13 @@ def delete_goal(goal_id): def assign_task_to_goal(goal_id): goal = validate_model(Goal, goal_id) task_ids = request.get_json().get("task_ids", []) - print("##### task_ids", task_ids, type(task_ids)) list_of_tasks = [] for task_id in task_ids: task = validate_model(Task, task_id) - print(">>>>", task.to_dict()) if task: list_of_tasks.append(task) - - print("$$$$", goal.tasks) - print("$$$$", [task.id for task in goal.tasks]) + goal.tasks.extend(list_of_tasks) db.session.commit() diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 44dabe291..59fc2a0b0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -53,8 +53,8 @@ def mark_task_incompleted(task_id): def send_task_complete_message(task_title): request_data = { - # "channel": "#api-test-channel", # Slack channel for tests - "channel": "U07GC9C8Y4X", # My Slack account ID + "channel": "#api-test-channel", # Slack channel for tests + # "channel": "U07GC9C8Y4X", # My Slack account ID "username": "Task List app", "text": f"Someone just completed the task \"{task_title}\"" } From d910bdfd1e23cd4766c12a272f141e95c0ce2303 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 9 Nov 2024 21:03:04 -0800 Subject: [PATCH 27/77] fix: a typo in Content_type --- app/routes/task_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 59fc2a0b0..08aa360c0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -63,9 +63,9 @@ def send_task_complete_message(task_title): json=request_data, headers={ "Authorization": environ.get('SLACK_API_KEY'), - "Content Type": "application/json" + "Content-Type": "application/json" }, - timeout=1 + timeout=5 ) return message_status.json()["ok"] From 490d343ee9a492f412bab6042d8161d977a7ce58 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sun, 10 Nov 2024 14:43:44 -0800 Subject: [PATCH 28/77] refactor: Adds descriptive error message to create_class_instance --- app/routes/route_utilities.py | 11 ++++++----- tests/test_wave_01.py | 8 ++------ tests/test_wave_05.py | 4 +--- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index f45b4293c..d4aee0046 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -29,11 +29,12 @@ def set_new_attributes(instance, req_body): def create_class_instance(cls, request, required_fields): req_body = request.get_json() - for param in required_fields: - if param not in req_body: - message = {"details": "Invalid data"} - abort(make_response(message, 400)) - new_instance = cls.from_dict(req_body) + try: + new_instance = cls.from_dict(req_body) + except KeyError as error: + message = {"details": f"Invalid request: missing {error.args[0]}"} + abort(make_response(message, 400)) + db.session.add(new_instance) db.session.commit() diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 0ef13143e..9302826cf 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -171,9 +171,7 @@ def test_create_task_must_contain_title(client): # Assert assert response.status_code == 400 assert "details" in response_body - assert response_body == { - "details": "Invalid data" - } + assert response_body == {"details": 'Invalid request: missing title'} assert Task.query.all() == [] @@ -188,7 +186,5 @@ def test_create_task_must_contain_description(client): # Assert assert response.status_code == 400 assert "details" in response_body - assert response_body == { - "details": "Invalid data" - } + assert response_body == {"details": 'Invalid request: missing description'} assert Task.query.all() == [] diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b996d86b9..4b4c5685e 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -140,6 +140,4 @@ def test_create_goal_missing_title(client): # Assert assert response.status_code == 400 - assert response_body == { - "details": "Invalid data" - } + assert response_body == {'details': 'Invalid request: missing title'} From 94df535f01a8834aaced5c9dcb0785272e9053bf Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 10:56:56 -0800 Subject: [PATCH 29/77] Adds Travis CI config file --- .tracis.yml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .tracis.yml diff --git a/.tracis.yml b/.tracis.yml new file mode 100644 index 000000000..95a7cea7a --- /dev/null +++ b/.tracis.yml @@ -0,0 +1,7 @@ +language: python +python: + - "3.12" +install: + - pip install -r requirements.txt +script: + - pytest \ No newline at end of file From cb0af0903d99e0d660fe5a18bca155991686c4e9 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 13:42:24 -0800 Subject: [PATCH 30/77] Changes python v in travis config --- .tracis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.tracis.yml b/.tracis.yml index 95a7cea7a..366266764 100644 --- a/.tracis.yml +++ b/.tracis.yml @@ -1,6 +1,7 @@ language: python python: - - "3.12" + - "3.9" + - "3.8" install: - pip install -r requirements.txt script: From e391da397c721a460334520a51eae6b162bbedb7 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 13:49:41 -0800 Subject: [PATCH 31/77] Changes python v in travis config --- .tracis.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.tracis.yml b/.tracis.yml index 366266764..0e1e0ed1a 100644 --- a/.tracis.yml +++ b/.tracis.yml @@ -4,5 +4,21 @@ python: - "3.8" install: - pip install -r requirements.txt +script: + - pytestlanguage: python +python: + - "2.7" + - "3.4" + - "3.5" + - "3.6" # current default Python on Travis CI + - "3.7" + - "3.8" + - "3.9" + - "3.9-dev" # 3.9 development branch + - "nightly" # nightly build +# command to install dependencies +install: + - pip install -r requirements.txt +# command to run tests script: - pytest \ No newline at end of file From e93fc24de91cd61a3c6a52bf903b3461b74b7330 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 13:59:06 -0800 Subject: [PATCH 32/77] Changes python v in travis config3 --- .tracis.yml | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 .tracis.yml diff --git a/.tracis.yml b/.tracis.yml deleted file mode 100644 index 0e1e0ed1a..000000000 --- a/.tracis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: python -python: - - "3.9" - - "3.8" -install: - - pip install -r requirements.txt -script: - - pytestlanguage: python -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" # current default Python on Travis CI - - "3.7" - - "3.8" - - "3.9" - - "3.9-dev" # 3.9 development branch - - "nightly" # nightly build -# command to install dependencies -install: - - pip install -r requirements.txt -# command to run tests -script: - - pytest \ No newline at end of file From edc1841e6d161dea911dab1c26c70f37239be3f0 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 14:04:46 -0800 Subject: [PATCH 33/77] Changes python v in travis config 4 --- .travis.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..77bcbd89e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,13 @@ +language: python +python: + - "3.9" + - "3.8" + - "3.7" + - "3.6" + - "3.5" + - "3.4" + - "2.7" +install: + - pip install -r requirements.txt +script: + - pytest \ No newline at end of file From 0039a99c9be593aadfbb79965a1b2b4b8fc98a71 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 14:44:30 -0800 Subject: [PATCH 34/77] Changes python v in travis config 5 --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 77bcbd89e..22b9d26f1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,4 +10,6 @@ python: install: - pip install -r requirements.txt script: - - pytest \ No newline at end of file + - pytest +after_success: +- render deploy --service --branch --token $RENDER_API_KEY \ No newline at end of file From f9521b9f737e7c11808f13777086b984187ce86f Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 14:44:54 -0800 Subject: [PATCH 35/77] Changes python v in travis config 5 --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 22b9d26f1..b6e47be48 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,10 +3,10 @@ python: - "3.9" - "3.8" - "3.7" - - "3.6" - - "3.5" - - "3.4" - - "2.7" + # - "3.6" + # - "3.5" + # - "3.4" + # - "2.7" install: - pip install -r requirements.txt script: From 3302239199e7d3b045f7db5846410b195313b4eb Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 14:48:11 -0800 Subject: [PATCH 36/77] Changes python v in travis config 6 --- .travis.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index b6e47be48..c2e54abed 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,5 +11,9 @@ install: - pip install -r requirements.txt script: - pytest -after_success: -- render deploy --service --branch --token $RENDER_API_KEY \ No newline at end of file +# after_success: +# - render deploy --service --branch --token $RENDER_API_KEY +before_install: + - sudo apt-get update + - sudo apt-get install -y openssl + - openssl version # Check if OpenSSL was updated to 1.1.1 or higher \ No newline at end of file From a6dcf4abaa14551f8d10c82e12ba17ae0d6085c0 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:00:25 -0800 Subject: [PATCH 37/77] Changes python v in travis config 7 --- .travis.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index c2e54abed..2b1b86dd0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,12 +8,9 @@ python: # - "3.4" # - "2.7" install: + - pip install urllib3<2.0 # Install a compatible version of urllib3 - pip install -r requirements.txt script: - pytest # after_success: # - render deploy --service --branch --token $RENDER_API_KEY -before_install: - - sudo apt-get update - - sudo apt-get install -y openssl - - openssl version # Check if OpenSSL was updated to 1.1.1 or higher \ No newline at end of file From b49f6a09cb79ea3c4f8554c500c3eb318be074d7 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:09:21 -0800 Subject: [PATCH 38/77] Changes python v in travis config 8 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2b1b86dd0..1c4a2d534 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ python: # - "3.4" # - "2.7" install: - - pip install urllib3<2.0 # Install a compatible version of urllib3 + - pip install "urllib3<2.0" # Correctly quoted version constraint - pip install -r requirements.txt script: - pytest From 2b734580bf5212da487f802088021e5b5c7be09d Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:11:58 -0800 Subject: [PATCH 39/77] Changes python v in travis config 9 --- .travis.yml | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1c4a2d534..e75c9f0f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,14 +3,11 @@ python: - "3.9" - "3.8" - "3.7" - # - "3.6" - # - "3.5" - # - "3.4" - # - "2.7" install: - - pip install "urllib3<2.0" # Correctly quoted version constraint + - sudo apt-get update + - sudo apt-get install -y openssl libssl-dev # Update OpenSSL + - openssl version # Verify OpenSSL version + - pip install "urllib3<2.0" # Correct version of urllib3 - pip install -r requirements.txt script: - - pytest -# after_success: -# - render deploy --service --branch --token $RENDER_API_KEY + - pytest \ No newline at end of file From 4c5440388e4dda2b19904ddbc4e2cdbcea0c40b9 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:15:05 -0800 Subject: [PATCH 40/77] Changes python v in travis config 10 --- .travis.yml | 12 +++++++----- requirements.txt | 3 ++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index e75c9f0f4..6ef420899 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,11 +3,13 @@ python: - "3.9" - "3.8" - "3.7" + # - "3.6" + # - "3.5" + # - "3.4" + # - "2.7" install: - - sudo apt-get update - - sudo apt-get install -y openssl libssl-dev # Update OpenSSL - - openssl version # Verify OpenSSL version - - pip install "urllib3<2.0" # Correct version of urllib3 - pip install -r requirements.txt script: - - pytest \ No newline at end of file + - pytest +# after_success: +# - render deploy --service --branch --token $RENDER_API_KEY diff --git a/requirements.txt b/requirements.txt index af8fc4cf4..49f82afab 100644 --- a/requirements.txt +++ b/requirements.txt @@ -22,5 +22,6 @@ python-dotenv==1.0.1 requests==2.32.3 SQLAlchemy==2.0.25 typing_extensions==4.9.0 -urllib3==2.2.3 +urllib3==2.0 +# urllib3==2.2.3 Werkzeug==3.0.1 From d32dfb3a5290d0ac6417a75e576baf8aa6705cd1 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:19:36 -0800 Subject: [PATCH 41/77] Changes python v in travis config 11 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 49f82afab..f65c25bc1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -22,6 +22,6 @@ python-dotenv==1.0.1 requests==2.32.3 SQLAlchemy==2.0.25 typing_extensions==4.9.0 -urllib3==2.0 +urllib3<2.0 # urllib3==2.2.3 Werkzeug==3.0.1 From 1ca3859048f42edb82520e03ae96f273f915e158 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:25:03 -0800 Subject: [PATCH 42/77] Changes python v in travis config 12 --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index 6ef420899..81c5e21a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,9 @@ python: # - "2.7" install: - pip install -r requirements.txt +before_script: + - echo $SLACK_API_KEY + - echo $SQLALCHEMY_DATABASE_URI script: - pytest # after_success: From 4d92b7dba4e478b4aad9c0cc8e40f36b30bfe268 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:34:53 -0800 Subject: [PATCH 43/77] Changes python v in travis config 13 --- .travis.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.travis.yml b/.travis.yml index 81c5e21a8..5b5e8fa77 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,14 @@ python: # - "2.7" install: - pip install -r requirements.txt + services: + - postgresql + +addons: + postgresql: "13" + before_script: + - psql -c 'create database task_list_api_test;' -U postgres - echo $SLACK_API_KEY - echo $SQLALCHEMY_DATABASE_URI script: From 3fee895e4785cf5c45a8bea04d224f733022c526 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:39:37 -0800 Subject: [PATCH 44/77] Changes python v in travis config 13 fixed --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5b5e8fa77..7f80d23e8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,7 @@ python: # - "2.7" install: - pip install -r requirements.txt - services: +services: - postgresql addons: From c440a7bd45b11e21bb8721b0184ace571f2ba30d Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:43:30 -0800 Subject: [PATCH 45/77] Changes python v in travis config 14 --- .travis.yml | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7f80d23e8..75a632bbd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,23 +3,27 @@ python: - "3.9" - "3.8" - "3.7" - # - "3.6" - # - "3.5" - # - "3.4" - # - "2.7" + install: - pip install -r requirements.txt + services: - postgresql addons: postgresql: "13" +env: + global: + - SQLALCHEMY_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test + before_script: - - psql -c 'create database task_list_api_test;' -U postgres - - echo $SLACK_API_KEY - - echo $SQLALCHEMY_DATABASE_URI + - echo "Starting PostgreSQL..." + - psql -c '\l' -U postgres # Проверить список баз + - psql -c 'create database task_list_api_test;' -U postgres || exit 1 + script: - pytest + # after_success: -# - render deploy --service --branch --token $RENDER_API_KEY +# - render deploy --service --branch --token $RENDER_API_KEY \ No newline at end of file From 069d7ecf53a9a2b76e5062abe8e28e0db79389f4 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:50:46 -0800 Subject: [PATCH 46/77] Changes python v in travis config 15 --- .travis.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 75a632bbd..2bfb20400 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,29 +1,29 @@ language: python python: - "3.9" - - "3.8" - - "3.7" - -install: - - pip install -r requirements.txt services: - postgresql addons: - postgresql: "13" + postgresql: "13" # Ensure PostgreSQL 13 is used env: global: - SQLALCHEMY_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test +before_install: + - sudo apt-get update + - sudo apt-get install -y postgresql-13 postgresql-client-13 # Explicitly install PostgreSQL 13 + before_script: - echo "Starting PostgreSQL..." - - psql -c '\l' -U postgres # Проверить список баз + - sudo systemctl restart postgresql # Restart PostgreSQL to ensure it starts properly + - psql --version # Verify psql version - psql -c 'create database task_list_api_test;' -U postgres || exit 1 -script: - - pytest +install: + - pip install -r requirements.txt -# after_success: -# - render deploy --service --branch --token $RENDER_API_KEY \ No newline at end of file +script: + - pytest \ No newline at end of file From 583722c66171149bf766bcfeff9459045cefb772 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 15:54:12 -0800 Subject: [PATCH 47/77] Changes python v in travis config 16 --- .travis.yml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2bfb20400..9ac70e8bb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +dist: focal # Используем Ubuntu 20.04 language: python python: - "3.9" @@ -6,7 +7,7 @@ services: - postgresql addons: - postgresql: "13" # Ensure PostgreSQL 13 is used + postgresql: "13" env: global: @@ -14,13 +15,14 @@ env: before_install: - sudo apt-get update - - sudo apt-get install -y postgresql-13 postgresql-client-13 # Explicitly install PostgreSQL 13 + - sudo apt-get install -y postgresql-13 postgresql-client-13 before_script: - echo "Starting PostgreSQL..." - - sudo systemctl restart postgresql # Restart PostgreSQL to ensure it starts properly - - psql --version # Verify psql version - - psql -c 'create database task_list_api_test;' -U postgres || exit 1 + - sudo sed -i 's/#port = 5432/port = 5432/' /etc/postgresql/13/main/postgresql.conf + - sudo systemctl restart postgresql || sudo service postgresql start + - psql --version + - psql -c 'create database task_list_api_test;' -U postgres || true install: - pip install -r requirements.txt From 3457fe49acde1d902615edd61ee4b346874efd67 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:11:04 -0800 Subject: [PATCH 48/77] Changes python v in travis config 17 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9ac70e8bb..7e6e24960 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,4 @@ -dist: focal # Используем Ubuntu 20.04 +dist: focal # Используем Ubuntu 20.04 для более свежей версии OpenSSL language: python python: - "3.9" @@ -23,6 +23,7 @@ before_script: - sudo systemctl restart postgresql || sudo service postgresql start - psql --version - psql -c 'create database task_list_api_test;' -U postgres || true + - psql -c '\l' -U postgres install: - pip install -r requirements.txt From ed09c673bb7cf85d2487574749f699b3e59d98de Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:24:00 -0800 Subject: [PATCH 49/77] Changes python v in travis config 18 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7e6e24960..06eef88de 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ addons: env: global: - - SQLALCHEMY_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test + - SQLALCHEMY_TEST_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test before_install: - sudo apt-get update From 6716d2a919a7741de7b65a55ede6640768ed1545 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 13:49:41 -0800 Subject: [PATCH 50/77] Changes python v in travis config Changes python v in travis config3 Changes python v in travis config 4 Changes python v in travis config 5 Changes python v in travis config 5 Changes python v in travis config 6 Changes python v in travis config 7 Changes python v in travis config 8 Changes python v in travis config 9 Changes python v in travis config 10 Changes python v in travis config 11 Changes python v in travis config 12 Changes python v in travis config 13 Changes python v in travis config 13 fixed Changes python v in travis config 14 Changes python v in travis config 15 Changes python v in travis config 16 Changes python v in travis config 17 Changes python v in travis config 18 --- .tracis.yml | 8 -------- .travis.yml | 32 ++++++++++++++++++++++++++++++++ requirements.txt | 3 ++- 3 files changed, 34 insertions(+), 9 deletions(-) delete mode 100644 .tracis.yml create mode 100644 .travis.yml diff --git a/.tracis.yml b/.tracis.yml deleted file mode 100644 index 366266764..000000000 --- a/.tracis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: python -python: - - "3.9" - - "3.8" -install: - - pip install -r requirements.txt -script: - - pytest \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..06eef88de --- /dev/null +++ b/.travis.yml @@ -0,0 +1,32 @@ +dist: focal # Используем Ubuntu 20.04 для более свежей версии OpenSSL +language: python +python: + - "3.9" + +services: + - postgresql + +addons: + postgresql: "13" + +env: + global: + - SQLALCHEMY_TEST_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test + +before_install: + - sudo apt-get update + - sudo apt-get install -y postgresql-13 postgresql-client-13 + +before_script: + - echo "Starting PostgreSQL..." + - sudo sed -i 's/#port = 5432/port = 5432/' /etc/postgresql/13/main/postgresql.conf + - sudo systemctl restart postgresql || sudo service postgresql start + - psql --version + - psql -c 'create database task_list_api_test;' -U postgres || true + - psql -c '\l' -U postgres + +install: + - pip install -r requirements.txt + +script: + - pytest \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index af8fc4cf4..f65c25bc1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -22,5 +22,6 @@ python-dotenv==1.0.1 requests==2.32.3 SQLAlchemy==2.0.25 typing_extensions==4.9.0 -urllib3==2.2.3 +urllib3<2.0 +# urllib3==2.2.3 Werkzeug==3.0.1 From 82fc58d73f711e58523ba0495f1e3102b0afdaf9 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:38:23 -0800 Subject: [PATCH 51/77] Adds instruction for deploy on Render --- .travis.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 06eef88de..9b51aaba0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,4 @@ -dist: focal # Используем Ubuntu 20.04 для более свежей версии OpenSSL +dist: focal language: python python: - "3.9" @@ -29,4 +29,9 @@ install: - pip install -r requirements.txt script: - - pytest \ No newline at end of file + - pytest + +after_success: + - echo "Deploying to Render..." + - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" \ + "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From 4eb37c0410e080140427b66fb811559aa5cc94b2 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:47:48 -0800 Subject: [PATCH 52/77] Adds instruction for deploy on Render 2 --- .travis.yml | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9b51aaba0..11e3fecf9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,37 +1,31 @@ +--- dist: focal language: python python: - "3.9" - services: - postgresql - addons: postgresql: "13" - env: global: - SQLALCHEMY_TEST_DATABASE_URI=postgresql+psycopg2://postgres@localhost:5432/task_list_api_test - before_install: - sudo apt-get update - sudo apt-get install -y postgresql-13 postgresql-client-13 - before_script: - echo "Starting PostgreSQL..." - - sudo sed -i 's/#port = 5432/port = 5432/' /etc/postgresql/13/main/postgresql.conf + - sudo sed -i 's/#port = 5432/port = 5432/' + /etc/postgresql/13/main/postgresql.conf - sudo systemctl restart postgresql || sudo service postgresql start - psql --version - psql -c 'create database task_list_api_test;' -U postgres || true - psql -c '\l' -U postgres - install: - pip install -r requirements.txt - script: - pytest - after_success: - echo "Deploying to Render..." - - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" \ - "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file + - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" + "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" From 5755c17e388990338768cda10f6d72297ad9cc97 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:56:48 -0800 Subject: [PATCH 53/77] Adds instruction for deploy on Render 3 --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 11e3fecf9..80a614b3a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,5 +27,5 @@ script: - pytest after_success: - echo "Deploying to Render..." - - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" - "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" + - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY \ + "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From 0db806a6acf7503fcd8e347c568f38df1f65c988 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 16:57:50 -0800 Subject: [PATCH 54/77] Adds instruction for deploy on Render 4 --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 80a614b3a..4951f4f23 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,5 +27,4 @@ script: - pytest after_success: - echo "Deploying to Render..." - - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY \ - "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file + - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From 321b6bd6f2d8f9661e6c87b6774f559256af3bf3 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 17:03:49 -0800 Subject: [PATCH 55/77] Adds instruction for deploy on Render 5 --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 4951f4f23..8bbd3642f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,4 +27,6 @@ script: - pytest after_success: - echo "Deploying to Render..." - - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file + # - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" + - curl --location --request POST 'https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM' --header 'Authorization: Bearer $RENDER_API_KEY' +# --header 'Cookie: __cf_bm=A4oQNGK8gQLyT.QHJYJ2jjze4pmrOLs4Wf3PiWRex.s-1732150898-1.0.1.1-rYYpXDUiddPWt.Q4H2ZvcNhc5FWuJ7UM3JdpJRUWLZ1wBRzUoVBvbCJeX5RHXkFeGmJyg6P.tGNu_ytkQlH5YQ' \ No newline at end of file From 485dac5db83a9f6d2b374b1c8af4374f2e2b314e Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 17:08:51 -0800 Subject: [PATCH 56/77] Adds instruction for deploy on Render 6 --- .travis.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8bbd3642f..762f1a7e3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,6 +27,5 @@ script: - pytest after_success: - echo "Deploying to Render..." - # - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" - - curl --location --request POST 'https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM' --header 'Authorization: Bearer $RENDER_API_KEY' -# --header 'Cookie: __cf_bm=A4oQNGK8gQLyT.QHJYJ2jjze4pmrOLs4Wf3PiWRex.s-1732150898-1.0.1.1-rYYpXDUiddPWt.Q4H2ZvcNhc5FWuJ7UM3JdpJRUWLZ1wBRzUoVBvbCJeX5RHXkFeGmJyg6P.tGNu_ytkQlH5YQ' \ No newline at end of file + - echo curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" + - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From a92db83e0b2a62e321a3c35c69513229976252c1 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Wed, 20 Nov 2024 17:13:14 -0800 Subject: [PATCH 57/77] Adds instruction for deploy on Render 7 --- .travis.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 762f1a7e3..ba651d569 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,11 +21,12 @@ before_script: - psql --version - psql -c 'create database task_list_api_test;' -U postgres || true - psql -c '\l' -U postgres + - curl --version install: - pip install -r requirements.txt script: - pytest after_success: - echo "Deploying to Render..." - - echo curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" - - curl -X POST -H "Authorization: Bearer $RENDER_API_KEY" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file + - echo "RENDER_API_KEY: ${RENDER_API_KEY}" + - curl -X POST -H "Authorization: Bearer ${RENDER_API_KEY}" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From 2e4dc64fed9d43f589660e5ec142229c4793be4e Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Thu, 21 Nov 2024 08:04:20 -0800 Subject: [PATCH 58/77] Adds instruction for deploy on Render 8 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ba651d569..46f217489 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,4 +29,4 @@ script: after_success: - echo "Deploying to Render..." - echo "RENDER_API_KEY: ${RENDER_API_KEY}" - - curl -X POST -H "Authorization: Bearer ${RENDER_API_KEY}" "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file + - curl -X POST "https://api.render.com/deploy/srv-csmrpdaj1k6c73dnhqi0?key=hVyereic-JM" \ No newline at end of file From 10c2c397ca2c7b27c9f2c3d88d8006cebc6d9e8b Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Mon, 2 Dec 2024 11:38:28 -0800 Subject: [PATCH 59/77] Breaking the code --- app/routes/route_utilities.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index d4aee0046..c2958c05f 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -6,21 +6,21 @@ def apply_filters(cls, arguments, query): if hasattr(cls, attribute): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) -def validate_model(cls, cls_id): - try: - cls_id = int(cls_id) - except ValueError: - message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} - abort(make_response(message, 400)) +# def validate_model(cls, cls_id): +# try: +# cls_id = int(cls_id) +# except ValueError: +# message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} +# abort(make_response(message, 400)) - query = db.select(cls).where(cls.id == cls_id) - result = db.session.scalar(query) +# query = db.select(cls).where(cls.id == cls_id) +# result = db.session.scalar(query) - if not result: - message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} - abort(make_response(message, 404)) +# if not result: +# message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} +# abort(make_response(message, 404)) - return result +# return result def set_new_attributes(instance, req_body): for attr, value in req_body.items(): From 721fe9413175e5196954c8872a04aa4d93d1480a Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Mon, 2 Dec 2024 11:41:43 -0800 Subject: [PATCH 60/77] Fixing the code --- app/routes/route_utilities.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index c2958c05f..d4aee0046 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -6,21 +6,21 @@ def apply_filters(cls, arguments, query): if hasattr(cls, attribute): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) -# def validate_model(cls, cls_id): -# try: -# cls_id = int(cls_id) -# except ValueError: -# message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} -# abort(make_response(message, 400)) +def validate_model(cls, cls_id): + try: + cls_id = int(cls_id) + except ValueError: + message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} + abort(make_response(message, 400)) -# query = db.select(cls).where(cls.id == cls_id) -# result = db.session.scalar(query) + query = db.select(cls).where(cls.id == cls_id) + result = db.session.scalar(query) -# if not result: -# message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} -# abort(make_response(message, 404)) + if not result: + message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} + abort(make_response(message, 404)) -# return result + return result def set_new_attributes(instance, req_body): for attr, value in req_body.items(): From 52da2dce9e41b75195c277b8090baeecee70f4e8 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Mon, 2 Dec 2024 11:45:17 -0800 Subject: [PATCH 61/77] Breaking the code --- app/routes/route_utilities.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index d4aee0046..89abaad82 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -7,18 +7,18 @@ def apply_filters(cls, arguments, query): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) def validate_model(cls, cls_id): - try: - cls_id = int(cls_id) - except ValueError: - message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} - abort(make_response(message, 400)) - - query = db.select(cls).where(cls.id == cls_id) - result = db.session.scalar(query) - - if not result: - message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} - abort(make_response(message, 404)) + # try: + # cls_id = int(cls_id) + # except ValueError: + # message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} + # abort(make_response(message, 400)) + + # query = db.select(cls).where(cls.id == cls_id) + # result = db.session.scalar(query) + + # if not result: + # message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} + # abort(make_response(message, 404)) return result From 2ffdc3fe573640eaee9a27add9e75ea6697e072e Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Mon, 2 Dec 2024 11:48:40 -0800 Subject: [PATCH 62/77] Fixing the code --- app/routes/route_utilities.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 89abaad82..d4aee0046 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -7,18 +7,18 @@ def apply_filters(cls, arguments, query): query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) def validate_model(cls, cls_id): - # try: - # cls_id = int(cls_id) - # except ValueError: - # message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} - # abort(make_response(message, 400)) - - # query = db.select(cls).where(cls.id == cls_id) - # result = db.session.scalar(query) - - # if not result: - # message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} - # abort(make_response(message, 404)) + try: + cls_id = int(cls_id) + except ValueError: + message = { "message": f"{cls.__name__} ID {cls_id} is invalid"} + abort(make_response(message, 400)) + + query = db.select(cls).where(cls.id == cls_id) + result = db.session.scalar(query) + + if not result: + message = {"message": f"{cls.__name__} with ID {cls_id} was not found"} + abort(make_response(message, 404)) return result From a2bf5ed8c7248cff31c48f84ba8d631161488903 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 17 Dec 2024 16:29:19 -0800 Subject: [PATCH 63/77] Fixed to work with local frontend --- app/__init__.py | 6 ++++-- app/routes/task_routes.py | 1 + requirements.txt | 6 +++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index a3fd2bd59..83bd0654d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,13 +1,15 @@ +from flask_cors import CORS from flask import Flask +import os from .routes.task_routes import bp as task_bp from .routes.goal_routes import bp as goal_bp from .db import db, migrate from .models import task, goal -import os + def create_app(config=None): app = Flask(__name__) - + CORS(app) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 08aa360c0..8d52d16ce 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -9,6 +9,7 @@ bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") + @bp.post("/", strict_slashes=False) def create_task(): return create_class_instance(Task, request, ["title", "description"]) diff --git a/requirements.txt b/requirements.txt index f65c25bc1..ea72e263f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,6 +4,7 @@ certifi==2024.8.30 charset-normalizer==3.3.2 click==8.1.7 Flask==3.0.2 +Flask-Cors==5.0.0 Flask-Migrate==4.0.5 Flask-SQLAlchemy==3.1.1 greenlet==3.0.3 @@ -19,9 +20,8 @@ pluggy==1.4.0 psycopg2-binary==2.9.9 pytest==8.0.0 python-dotenv==1.0.1 -requests==2.32.3 +requests==2.31.0 SQLAlchemy==2.0.25 typing_extensions==4.9.0 -urllib3<2.0 -# urllib3==2.2.3 +urllib3==2.0.7 Werkzeug==3.0.1 From 1b513876d63f12849755e256c6781ff7f7293580 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Tue, 17 Dec 2024 21:38:46 -0800 Subject: [PATCH 64/77] Add render.yaml --- render.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 render.yaml diff --git a/render.yaml b/render.yaml new file mode 100644 index 000000000..333803cea --- /dev/null +++ b/render.yaml @@ -0,0 +1,12 @@ +# Exported from Render on 2024-12-18T05:36:46Z +databases: +- name: task_list-db + databaseName: task_list_db_2l3f + user: task_list_db_2l3f_user + plan: free + region: oregon + ipAllowList: + - source: 0.0.0.0/0 + description: everywhere + postgresMajorVersion: "16" +version: "1" From 09f89e942859a643f6f1e4b1ae545a3186dde9b4 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Fri, 3 Jan 2025 17:17:18 -0800 Subject: [PATCH 65/77] log for debugging the server version of backend --- app/routes/task_routes.py | 1 + 1 file changed, 1 insertion(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 8d52d16ce..98a84d3ab 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -68,5 +68,6 @@ def send_task_complete_message(task_title): }, timeout=5 ) + print(message_status) return message_status.json()["ok"] From 363fb620350905ae1cac47d07171f0f5f1fc5f19 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 12:50:04 -0800 Subject: [PATCH 66/77] configurates CORS --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 83bd0654d..7470ff0c9 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,7 +9,7 @@ def create_app(config=None): app = Flask(__name__) - CORS(app) + CORS(app, resources={r"/*": {"origins": ["http://localhost:5173", "https://task-list-api-a1l3.onrender.com/tasks"]}}) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') From 5ceb0590918835571485e95894a08c2cb31a6d45 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 12:54:57 -0800 Subject: [PATCH 67/77] configurates CORS --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 7470ff0c9..73de08bd6 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,7 +9,7 @@ def create_app(config=None): app = Flask(__name__) - CORS(app, resources={r"/*": {"origins": ["http://localhost:5173", "https://task-list-api-a1l3.onrender.com/tasks"]}}) + CORS(app, resources={r"/*": {"origins": ["http://localhost:5173", "https://task-list-api-a1l3.onrender.com"]}}) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') From f22a456dbaea261eb6f702ec827e7150542bff6c Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:05:47 -0800 Subject: [PATCH 68/77] fixing notofocations in deployed BE --- app/routes/task_routes.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 98a84d3ab..6824301bc 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -36,12 +36,12 @@ def mark_task_completed(task_id): task.completed_at = datetime.now() db.session.commit() - message_is_sent = send_task_complete_message(task.title) + try: + send_task_complete_message(task.title) - if not message_is_sent: - raise Exception( - "An error occured during notification sending!\ - Please connect to the Task List developer!") + except Exception as e: + raise Exception("An error occurred during notification sending! Please connect to the Task List developer!") from e + return { "task": task.to_dict() }, 200 @bp.patch("//mark_incomplete") @@ -53,6 +53,7 @@ def mark_task_incompleted(task_id): return { "task": task.to_dict() }, 200 def send_task_complete_message(task_title): + print(os.environ.get('SLACK_API_KEY')) request_data = { "channel": "#api-test-channel", # Slack channel for tests # "channel": "U07GC9C8Y4X", # My Slack account ID From acca02ac027100a2006e3e9060ac40f14315db3b Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:11:45 -0800 Subject: [PATCH 69/77] fixing notofocations in deployed BE --- app/routes/task_routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 6824301bc..065d62603 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -53,7 +53,7 @@ def mark_task_incompleted(task_id): return { "task": task.to_dict() }, 200 def send_task_complete_message(task_title): - print(os.environ.get('SLACK_API_KEY')) + print(environ.get('SLACK_API_KEY')) request_data = { "channel": "#api-test-channel", # Slack channel for tests # "channel": "U07GC9C8Y4X", # My Slack account ID From c2e586d6b8df9d406c99bef8662948bd0ed313a3 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:33:57 -0800 Subject: [PATCH 70/77] fixing notofocations in deployed BE --- app/routes/task_routes.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 065d62603..ae20b4947 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -70,5 +70,9 @@ def send_task_complete_message(task_title): timeout=5 ) print(message_status) + print('____________________________________________') + print(message_status.json()['message']) + print('____________________________________________') + print(message_status.json()) return message_status.json()["ok"] From 5c178ddf56bfa190cde190f10f5256b31da5b8b4 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:40:29 -0800 Subject: [PATCH 71/77] fixing notofocations in deployed BE --- app/routes/task_routes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ae20b4947..988c552b4 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -71,8 +71,9 @@ def send_task_complete_message(task_title): ) print(message_status) print('____________________________________________') - print(message_status.json()['message']) + # print(message_status.json()['message']) + print(message_status.ok) print('____________________________________________') - print(message_status.json()) + print(message_status.error) return message_status.json()["ok"] From 53f779ccbff342fc9187af177948d84fb145a9de Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:54:19 -0800 Subject: [PATCH 72/77] fixing notofocations in deployed BE --- app/routes/task_routes.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 988c552b4..486aa6e90 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -53,7 +53,6 @@ def mark_task_incompleted(task_id): return { "task": task.to_dict() }, 200 def send_task_complete_message(task_title): - print(environ.get('SLACK_API_KEY')) request_data = { "channel": "#api-test-channel", # Slack channel for tests # "channel": "U07GC9C8Y4X", # My Slack account ID @@ -69,11 +68,5 @@ def send_task_complete_message(task_title): }, timeout=5 ) - print(message_status) - print('____________________________________________') - # print(message_status.json()['message']) - print(message_status.ok) - print('____________________________________________') - print(message_status.error) return message_status.json()["ok"] From 6052392eafe9c17b6715e9e6feb5792945e00834 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 13:05:47 -0800 Subject: [PATCH 73/77] fixing notofocations in deployed BE fixing notofocations in deployed BE fixing notofocations in deployed BE fixing notofocations in deployed BE fixing notofocations in deployed BE --- app/routes/task_routes.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 98a84d3ab..486aa6e90 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -36,12 +36,12 @@ def mark_task_completed(task_id): task.completed_at = datetime.now() db.session.commit() - message_is_sent = send_task_complete_message(task.title) + try: + send_task_complete_message(task.title) - if not message_is_sent: - raise Exception( - "An error occured during notification sending!\ - Please connect to the Task List developer!") + except Exception as e: + raise Exception("An error occurred during notification sending! Please connect to the Task List developer!") from e + return { "task": task.to_dict() }, 200 @bp.patch("//mark_incomplete") @@ -68,6 +68,5 @@ def send_task_complete_message(task_title): }, timeout=5 ) - print(message_status) return message_status.json()["ok"] From 011e93686d846c2dac4211d09b5ee7fee528d7f9 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 17:35:21 -0800 Subject: [PATCH 74/77] adds gh-pages address to CORS configs --- app/__init__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 73de08bd6..ee7d8247b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,9 +9,14 @@ def create_app(config=None): app = Flask(__name__) - CORS(app, resources={r"/*": {"origins": ["http://localhost:5173", "https://task-list-api-a1l3.onrender.com"]}}) + CORS(app, resources={r"/*": {"origins": [ + "http://localhost:5173", + "https://task-list-api-a1l3.onrender.com", + "https://nerpassevera.github.io" + ]}}) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + 'SQLALCHEMY_DATABASE_URI') if config: # Merge `config` into the app's configuration From c904e75ce65e640b6fed1632717926888c776d9a Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 18:32:01 -0800 Subject: [PATCH 75/77] Updates README --- README.md | 150 ++++++++++++++++++++++--------- ada-project-docs/instructions.md | 57 ++++++++++++ 2 files changed, 166 insertions(+), 41 deletions(-) create mode 100644 ada-project-docs/instructions.md diff --git a/README.md b/README.md index 85e1c0f69..69cde330d 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,125 @@ -# Task List API -## Skills Assessed +# Task List API Backend -- Gathering technical requirements from written documentation -- Reading, writing, and using tests -- Demonstrating understanding of the client-server model, request-response cycle and conventional RESTful routes -- Driving development with independent research, experimentation, and collaboration -- Reading and using existing external web APIs -- Using Postman as part of the development workflow -- Using git as part of the development workflow +A backend RESTful API built with Flask to manage tasks and goals in a full-stack project. The API is integrated with a PostgreSQL database and provides endpoints for creating, reading, updating, and deleting tasks and goals. + +## About the Project + +This backend application is part of a full-stack project created to practice and strengthen skills in backend development, API design, and database integration. It serves as the server-side component of the TaskList application. + +### Deployed Application + +- **Backend Deployment**: [Deployed Backend on Render](https://task-list-api-ai13.onrender.com) +- **Frontend Deployment**: [Deployed Frontend on GitHub Pages](https://nerpassevera.github.io/task-list-front-end) + +## Features + +### Tasks +- **Create Tasks**: Add new tasks. +- **Delete Tasks**: Remove tasks from the list. +- **Read Tasks**: Retrieve all tasks or a single task. +- **Update Tasks**: Update task information. +- **Mark Tasks as Completed/Incompleted**: Change the task status. +- **Slack Notifications**: Notify a Slack channel when a task is marked as completed. -Working with the Flask package: +### Goals +- **Create Goals**: Add new goals. +- **Delete Goals**: Remove goals from the list. +- **Read Goals**: Retrieve all goals or a single goal. +- **Update Goals**: Update goal information. +- **Assign Tasks to Goals**: Link multiple tasks to specific goals. -- Creating models -- Creating conventional RESTful CRUD routes for a model -- Reading query parameters to create custom behavior -- Create unconventional routes for custom behavior -- Apply knowledge about making requests in Python, to call an API inside of an API -- Apply knowledge about environment variables -- Creating a one-to-many relationship between two models +## Technologies Used -## Goals +- **Flask**: Lightweight web framework for Python. +- **SQLAlchemy**: ORM for database management. +- **Alembic**: Database migration tool. +- **PostgreSQL**: Relational database for storing tasks and goals. +- **Flask-CORS**: Manage Cross-Origin Resource Sharing for API. +- **Python-dotenv**: Manage environment variables using a `.env` file. -There's so much we want to do in the world! When we organize our goals into smaller, bite-sized tasks, we'll be able to track them more easily, and complete them! +## API Endpoints -If we make a web API to organize our tasks, we'll be able to create, read, update, and delete tasks as long as we have access to the Internet and our API is running! +### Tasks Routes -We also want to do some interesting features with our tasks. We want to be able to: +| Method | Endpoint | Description | +|----------|-----------------------------|------------------------------------------| +| GET | `/tasks` | Retrieve all tasks. | +| POST | `/tasks` | Create a new task. | +| GET | `/tasks/` | Retrieve a specific task by ID. | +| PUT | `/tasks/` | Update a specific task by ID. | +| DELETE | `/tasks/` | Delete a specific task by ID. | +| PATCH | `/tasks//mark_complete` | Mark a task as completed. | +| PATCH | `/tasks//mark_incomplete` | Mark a task as incomplete. | -- Sort tasks -- Mark them as complete -- Get feedback about our task list through Slack -- Organize tasks with goals +### Goals Routes -... and more! +| Method | Endpoint | Description | +|----------|-----------------------------|------------------------------------------| +| GET | `/goals` | Retrieve all goals. | +| POST | `/goals` | Create a new goal. | +| GET | `/goals/` | Retrieve a specific goal by ID. | +| PUT | `/goals/` | Update a specific goal by ID. | +| DELETE | `/goals/` | Delete a specific goal by ID. | +| POST | `/goals//tasks` |Assign multiple tasks to a specific goal. | +| GET | `/goals//tasks` |Retrieve all tasks associated with a goal.| -## How to Complete and Submit +## Setup Instructions -Go through the waves one-by-one and build the features of this API. +### Prerequisites +- Python 3.12 or higher +- PostgreSQL -At submission time, no matter where you are, submit the project via Learn. +### Installation -## Project Directions +1. Clone the repository: + ```bash + git clone https://github.com/Nerpassevera/task-list-api.git + cd task-list-api + ``` -This project is designed to fulfill the features described in detail in each wave. The tests are meant to only guide your development. +2. Create and activate a virtual environment: + ```bash + python3 -m venv venv + source venv/bin/activate # On Linux/macOS + venv\Scripts\activate # On Windows + ``` -1. [Setup](ada-project-docs/setup.md) -1. [Testing](ada-project-docs/testing.md) -1. [Wave 1: CRUD for one model](ada-project-docs/wave_01.md) -1. [Wave 2: Using query params](ada-project-docs/wave_02.md) -1. [Wave 3: Creating custom endpoints](ada-project-docs/wave_03.md) -1. [Wave 4: Using an external web API](ada-project-docs/wave_04.md) -1. [Wave 5: Creating a second model](ada-project-docs/wave_05.md) -1. [Wave 6: Establishing a one-to-many relationship between two models](ada-project-docs/wave_06.md) -1. [Wave 7: Deployment](ada-project-docs/wave_07.md) -1. [Optional Enhancements](ada-project-docs/optional-enhancements.md) +3. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +4. Set up environment variables: + ```bash + cp .env.example .env + ``` + + Update `.env` with your database URL and Slack API key: + ``` + SQLALCHEMY_DATABASE_URI= + SLACK_API_KEY= + ``` + +5. Run database migrations: + ```bash + flask db upgrade + ``` + +6. Start the development server: + ```bash + flask run + ``` + +## Future Plans + +- Allow users to dynamically change the Slack channel for notifications. +- Create user accounts + +## Author + +- [Tatiana Trofimova](https://github.com/Nerpassevera) + +## License + +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. diff --git a/ada-project-docs/instructions.md b/ada-project-docs/instructions.md new file mode 100644 index 000000000..85e1c0f69 --- /dev/null +++ b/ada-project-docs/instructions.md @@ -0,0 +1,57 @@ +# Task List API + +## Skills Assessed + +- Gathering technical requirements from written documentation +- Reading, writing, and using tests +- Demonstrating understanding of the client-server model, request-response cycle and conventional RESTful routes +- Driving development with independent research, experimentation, and collaboration +- Reading and using existing external web APIs +- Using Postman as part of the development workflow +- Using git as part of the development workflow + +Working with the Flask package: + +- Creating models +- Creating conventional RESTful CRUD routes for a model +- Reading query parameters to create custom behavior +- Create unconventional routes for custom behavior +- Apply knowledge about making requests in Python, to call an API inside of an API +- Apply knowledge about environment variables +- Creating a one-to-many relationship between two models + +## Goals + +There's so much we want to do in the world! When we organize our goals into smaller, bite-sized tasks, we'll be able to track them more easily, and complete them! + +If we make a web API to organize our tasks, we'll be able to create, read, update, and delete tasks as long as we have access to the Internet and our API is running! + +We also want to do some interesting features with our tasks. We want to be able to: + +- Sort tasks +- Mark them as complete +- Get feedback about our task list through Slack +- Organize tasks with goals + +... and more! + +## How to Complete and Submit + +Go through the waves one-by-one and build the features of this API. + +At submission time, no matter where you are, submit the project via Learn. + +## Project Directions + +This project is designed to fulfill the features described in detail in each wave. The tests are meant to only guide your development. + +1. [Setup](ada-project-docs/setup.md) +1. [Testing](ada-project-docs/testing.md) +1. [Wave 1: CRUD for one model](ada-project-docs/wave_01.md) +1. [Wave 2: Using query params](ada-project-docs/wave_02.md) +1. [Wave 3: Creating custom endpoints](ada-project-docs/wave_03.md) +1. [Wave 4: Using an external web API](ada-project-docs/wave_04.md) +1. [Wave 5: Creating a second model](ada-project-docs/wave_05.md) +1. [Wave 6: Establishing a one-to-many relationship between two models](ada-project-docs/wave_06.md) +1. [Wave 7: Deployment](ada-project-docs/wave_07.md) +1. [Optional Enhancements](ada-project-docs/optional-enhancements.md) From 051049f8fa9d063278063a7eff436287eada1d70 Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova <63259752+Nerpassevera@users.noreply.github.com> Date: Sat, 4 Jan 2025 18:33:48 -0800 Subject: [PATCH 76/77] Create LICENSE --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..8db21ae45 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Tatiana Trofimova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 650791987a5f7e78449040eb18789b33569a2dea Mon Sep 17 00:00:00 2001 From: Tatiana Trofimova Date: Sat, 4 Jan 2025 18:37:03 -0800 Subject: [PATCH 77/77] Updates README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 69cde330d..04222c750 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ This backend application is part of a full-stack project created to practice and ## Future Plans +- Create a meta route with information of endpoints available - Allow users to dynamically change the Slack channel for notifications. - Create user accounts