diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..88d6331cf 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,12 +4,10 @@ import os from dotenv import load_dotenv - db = SQLAlchemy() migrate = Migrate() load_dotenv() - def create_app(test_config=None): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False @@ -30,5 +28,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from .task_routes import tasks_bp + app.register_blueprint(tasks_bp) + from .goal_routes import goals_bp + app.register_blueprint(goals_bp) return app diff --git a/app/goal_routes.py b/app/goal_routes.py new file mode 100644 index 000000000..20876cd70 --- /dev/null +++ b/app/goal_routes.py @@ -0,0 +1,87 @@ +from flask import Blueprint, jsonify, abort, request +from app import db +from app.models.goal import Goal +from app.models.task import Task +from dotenv import load_dotenv + +load_dotenv() + +goals_bp = Blueprint("goal", __name__, url_prefix="/goals") + +def valid_id(model, id): + """If ID is an int, returns the model object with that ID. + If ID is not an int, returns 400. + If model object with that ID doesn't exist, returns 404.""" + try: + id = int(id) + except: + abort(400, {"error": "invalid id"}) + return model.query.get_or_404(id) + +@goals_bp.route("", methods=["POST", "GET"]) +def handle_goals(): + """Handles post and get requests for /goals""" + request_body = request.get_json() + + if request.method == "POST": + if "title" not in request_body: + return {"details": "Invalid data"}, 400 + + new_goal = Goal(title=request_body["title"]) + + db.session.add(new_goal) + db.session.commit() + + goals_dict = {} + goals_dict["goal"] = new_goal.to_dict() + return goals_dict, 201 + + if request.method == "GET": + goals = Goal.query.all() + goals_response = [goal.to_dict() for goal in goals] + + return jsonify(goals_response), 200 + +@goals_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_one_goal(goal_id): + """Handles get, put, and delete requests for one goal \ + with a given id at goals/""" + goal_dict = {} + goal = valid_id(Goal, goal_id) + + if request.method == "GET": + goal_dict["goal"] = goal.to_dict() + return goal_dict, 200 + + if request.method == "PUT": + request_body = request.get_json() + goal.title = request_body["title"] + goal_dict["goal"] = goal.to_dict() + db.session.commit() + return goal_dict, 200 + + if request.method == "DELETE": + if goal: + db.session.delete(goal) + db.session.commit() + return {"details": f"Goal {goal.goal_id} \"{goal.title}\" successfully deleted"}, 200 + +@goals_bp.route("//tasks", methods=["POST", "GET"]) +def handle_tasks_realted_to_goal(goal_id): + """Handles post and get requets for a goal with a given ID \ + and all tasks related to it at /goals//tasks""" + goal = valid_id(Goal, goal_id) + + if request.method == "POST": + request_body = request.get_json() + goal.tasks = [valid_id(Task, task_id) for task_id in request_body["task_ids"]] + + db.session.commit() + + return {"id": int(goal_id), "task_ids": request_body["task_ids"]}, 200 + + if request.method == "GET": + goal_dict = goal.to_dict() + goal_dict["tasks"] = [valid_id(Task, task.task_id).to_dict() for task in goal.tasks] + + return goal_dict, 200 diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..707a13b51 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,14 @@ -from flask import current_app from app import db - class Goal(db.Model): + """"Database model with goal_id, title, and a backref relationship to tasks""" goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.Text, nullable=False) + tasks = db.relationship("Task", backref="goal", lazy=True) + + def to_dict(self): + """Returns a dictionary with Goal ID and title.""" + return({ + "id": self.goal_id, + "title": self.title + }) \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..450f45e81 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,40 @@ from flask import current_app from app import db - class Task(db.Model): + """Database model with task_id, title, description, \ + data and time for completion, \ + and relationship with the one goal it is connected to""" task_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime, nullable=True) + goal_id = db.Column(db.Integer, db.ForeignKey("goal.goal_id"), nullable=True) + + def to_dict(self): + """Returns a dictionary with Task id, title, description, T/F is_complete,\ + and goal_ids IF goal_ids are present.""" + is_complete = True + if not self.completed_at: + is_complete = False + + if not self.goal_id: + return({ + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": is_complete + }) + + else: + return({ + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": is_complete, + "goal_id": self.goal_id + }) + + + + diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 8e9dfe684..000000000 --- a/app/routes.py +++ /dev/null @@ -1,2 +0,0 @@ -from flask import Blueprint - diff --git a/app/task_routes.py b/app/task_routes.py new file mode 100644 index 000000000..3a54b3a55 --- /dev/null +++ b/app/task_routes.py @@ -0,0 +1,119 @@ +from flask import Blueprint, jsonify, abort, request +from app import db +from app.models.task import Task +from datetime import datetime +import requests +import os +from dotenv import load_dotenv + +load_dotenv() + +tasks_bp = Blueprint("task", __name__, url_prefix="/tasks") + +def valid_id(model, id): + """If ID is an int, returns the model object with that ID. + If ID is not an int, returns 400. + If model object with that ID doesn't exist, returns 404.""" + try: + id = int(id) + except: + abort(400, {"error": "invalid id"}) + return model.query.get_or_404(id) + +@tasks_bp.route("", methods=["POST", "GET"]) +def handle_tasks(): + """Handles post and get requests for tasks at /tasks""" + request_body = request.get_json() + + if request.method == "POST": + if "title" not in request_body or "description" not in request_body \ + or "completed_at" not in request_body: + return {"details": "Invalid data"}, 400 + + new_task = Task(title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"]) + + db.session.add(new_task) + db.session.commit() + + tasks_dict = {} + tasks_dict["task"] = new_task.to_dict() + return tasks_dict, 201 + + if request.method == "GET": + tasks_response = [] + if request.args.get("sort") == "asc": + tasks = Task.query.order_by(Task.title) + elif request.args.get("sort") == "desc": + tasks = Task.query.order_by(Task.title.desc()) + else: + tasks = Task.query.all() + for task in tasks: + tasks_response.append(task.to_dict()) + + return jsonify(tasks_response), 200 + +@tasks_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_one_task(task_id): + """Handles get, put, and delete requests \ + for one task with a given id at /tasks/""" + task_dict = {} + task = valid_id(Task, task_id) + + if request.method == "GET": + task_dict["task"] = task.to_dict() + return task_dict, 200 + + if request.method == "PUT": + input_data = request.get_json() + task.title = input_data["title"] + task.description = input_data["description"] + if task.completed_at: + task.completed_at = input_data["completed_at"] + task_dict["task"] = task.to_dict() + db.session.commit() + return task_dict, 200 + + if request.method == "DELETE": + if task: + db.session.delete(task) + db.session.commit() + return {'details': f'Task {task.task_id} "{task.title}" successfully deleted'}, 200 + +def post_task_completion_to_slack(task): + """Posts a message to slack stating that someone completed a task with the task title""" + SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN") + SLACK_CHANNEL = os.environ.get("SLACK_CHANNEL") + url = "https://slack.com/api/chat.postMessage" + message = f"Somone just completed task {task.title}" + query_params = { + "channel": SLACK_CHANNEL, + "text": message + } + headers = { + "Authorization": f"Bearer {SLACK_BOT_TOKEN}" + } + # response variable left for debugging purposes + response = requests.post(url, data=query_params, headers=headers) + + +@tasks_bp.route("//", methods=["PATCH"]) +def mark_completion_status(task_id, completion_status): + """Returns task_dict and changes value of task.completed_at. \ + If user goes to /tasks//mark_complete, \ + task.completed_at has a value of current date and time \ + and a message is posted to slack. + If user goes to /tasks//mark_incomplete, \ + task.completed_at has a value of None""" + task_dict = {} + task = valid_id(Task, task_id) + + if completion_status == "mark_complete": + task.completed_at = datetime.date + post_task_completion_to_slack(task) + elif completion_status == "mark_incomplete": + task.completed_at = None + + task_dict["task"] = task.to_dict() + return task_dict, 200 diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/0a4169bfecf1_.py b/migrations/versions/0a4169bfecf1_.py new file mode 100644 index 000000000..7ee762e1e --- /dev/null +++ b/migrations/versions/0a4169bfecf1_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 0a4169bfecf1 +Revises: +Create Date: 2021-10-27 13:47:14.576470 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0a4169bfecf1' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('task_id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/migrations/versions/4d1b8e122bec_.py b/migrations/versions/4d1b8e122bec_.py new file mode 100644 index 000000000..819d047f4 --- /dev/null +++ b/migrations/versions/4d1b8e122bec_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 4d1b8e122bec +Revises: fa01e41ea079 +Create Date: 2021-11-03 19:45:44.612693 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4d1b8e122bec' +down_revision = 'fa01e41ea079' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'task', 'goal', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### diff --git a/migrations/versions/fa01e41ea079_.py b/migrations/versions/fa01e41ea079_.py new file mode 100644 index 000000000..6ba9928d8 --- /dev/null +++ b/migrations/versions/fa01e41ea079_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: fa01e41ea079 +Revises: 0a4169bfecf1 +Create Date: 2021-11-03 13:41:55.287209 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fa01e41ea079' +down_revision = '0a4169bfecf1' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('title', sa.Text(), nullable=False)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('goal', 'title') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index cfdf74050..c86437c87 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,17 @@ +aiohttp==3.8.0 +aiosignal==1.2.0 alembic==1.5.4 +async-timeout==4.0.0 attrs==20.3.0 autopep8==1.5.5 certifi==2020.12.5 chardet==4.0.0 +charset-normalizer==2.0.7 click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +frozenlist==1.2.0 gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 @@ -14,6 +19,7 @@ itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +multidict==5.2.0 packaging==20.9 pluggy==0.13.1 psycopg2-binary==2.8.6 @@ -26,7 +32,11 @@ python-dotenv==0.15.0 python-editor==1.0.4 requests==2.25.1 six==1.15.0 +slack==0.0.2 +slackclient==2.9.3 SQLAlchemy==1.3.23 toml==0.10.2 +typing-extensions==3.10.0.2 urllib3==1.26.4 Werkzeug==1.0.1 +yarl==1.7.2 diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 6ba60c6fa..af1a40d8c 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,4 +1,5 @@ import pytest +from app.models.goal import Goal def test_get_goals_no_saved_goals(client): # Act @@ -41,7 +42,6 @@ def test_get_goal(client, one_goal): } } -@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act @@ -49,10 +49,9 @@ def test_get_goal_not_found(client): response_body = response.get_json() # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == None + def test_create_goal(client): # Act @@ -71,30 +70,36 @@ def test_create_goal(client): } } -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - pass # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title" + } + } + goal = Goal.query.get(1) + assert goal.title == "Updated Goal Title" -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - pass # Act - # ---- Complete Act Here ---- + response = client.put("/tasks/1", json={ + "title": "Updated Task Title", + "description": "Updated Test Description", + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None def test_delete_goal(client, one_goal): @@ -113,18 +118,15 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 -@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - pass - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None + assert Goal.query.all() == [] def test_create_goal_missing_title(client):