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..a9dc6d503 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -22,13 +22,19 @@ def create_app(test_config=None): app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") - # Import models here for Alembic setup - from app.models.task import Task - from app.models.goal import Goal db.init_app(app) migrate.init_app(app, db) # Register Blueprints here + from .routes import tasks_bp + from .routes import goals_bp + + app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) + + from app.models.task import Task + from app.models.goal import Goal + return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..d4c72f520 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,28 @@ from flask import current_app from app import db - +from app.models.task import Task class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + __tablename__ = 'goal' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + #these are not just IDs, like a list of numbers...they are objects of type Task + tasks = db.relationship("Task", backref="goal", lazy=True) + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + } + + + def goal_tasks_to_dict(self): + mytasks = Task.query.all(self[0].tasks) + mylist = [] + for thing in mytasks: + mylist.append(thing.id) + + return { + "id": self.id, + "task_ids": mylist + } \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..9d83edefd 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -3,4 +3,22 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + __tablename__ = 'task' + id = db.Column(db.Integer, primary_key=True, autoincrement=True ) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime, nullable=True) + goal_id = db.Column(db.Integer, db.ForeignKey("goal.id"), nullable=True) + + def to_dict(self): + result = { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": True if self.completed_at else False + } + + if self.goal_id: + result["goal_id"]=self.goal_id + return result + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..62f452e66 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,188 @@ -from flask import Blueprint +from flask import Blueprint, jsonify, request, make_response +from flask.globals import session +from app import db +from app.models.task import Task +from app.models.goal import Goal +from sqlalchemy import asc, desc +from datetime import datetime +import requests +import urllib.parse +from dotenv import load_dotenv +import os + +load_dotenv() + +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals",__name__, url_prefix="/goals") + +@tasks_bp.route("", methods=["POST","GET"], strict_slashes=False) +def create_task(): + if request.method == "POST": + request_body = request.get_json() + if ("title" not in request_body) or ("description" not in request_body) or ("completed_at" not in request_body): + return {"details": "Invalid data"}, 400 + else: + 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() + if request_body['completed_at'] == None: + return make_response({"task":new_task.to_dict()}), 201 + else: + return make_response({"task":new_task.to_dict()}), 201 + elif request.method == "GET": + if "sort" in request.args: + title_sorter = request.args.get("sort") + if title_sorter == "asc": + tasks_list = Task.query.order_by(Task.title.asc()).all() + elif title_sorter == "desc": + tasks_list = Task.query.order_by(Task.title.desc()).all() + else: + tasks_list = Task.query.all() + response = [] + for my_task in tasks_list: + response.append(my_task.to_dict()) + return jsonify(response), 200 + +@tasks_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def get_task(task_id): + task_id = int(task_id) + my_task = Task.query.get(task_id) + if request.method == "GET": + if my_task is None: + return "", 404 + else: + return make_response({"task":my_task.to_dict()}), 200 + + elif request.method == "PUT": + request_body = request.get_json() + try: + my_task.title = request_body["title"] + my_task.description = request_body["description"] + if "completed_at" in request_body : + my_task.completed_at = request_body["completed_at"] + db.session.commit() + return make_response({"task":my_task.to_dict()}), 200 + except AttributeError as ae: + return make_response("", 404) + + elif request.method == "DELETE": + if my_task is None: + return "", 404 + else: + db.session.delete(my_task) + db.session.commit() + myResponse = 'Task ' + str(task_id) + ' "' + my_task.title + '" successfully deleted' + return make_response({"details":myResponse}), 200 + +@tasks_bp.route("//", methods=["PATCH"], strict_slashes=False ) +def mark_complete(task_id, completed_status): + task_id = int(task_id) + my_task = Task.query.get(task_id) + if request.method == "PATCH": + if my_task is None: + return "", 404 + else: + if completed_status == "mark_complete": + my_task.completed_at = datetime.now() + send_slack_notice(my_task.title) + elif completed_status == "mark_incomplete": + my_task.completed_at = None + db.session.commit() + return make_response({"task" : my_task.to_dict()}), 200 + + +def send_slack_notice(this_task_title): + #here we need to create an http.request to the slack end point + myNotice = urllib.parse.quote_plus("Someone just completed the task " + this_task_title) + my_url = "https://slack.com/api/chat.postMessage?channel=task-notifications&text=" + myNotice + "&pretty=1" + #add a request.header "Authorization", "super secret" + my_token = os.environ.get("MY_SLACK_TOKEN") + my_headers = {"Authorization": f"Bearer {my_token}"} + #send + r = requests.post(my_url, data="", headers=my_headers) + +@goals_bp.route("", methods=["GET", "POST"], strict_slashes=False) +def create_goal(): + if request.method == "POST": + request_body = request.get_json() + if "title" not in request_body: + return {"details": "Invalid data"}, 400 + else: + new_goal = Goal(title=request_body['title']) + db.session.add(new_goal) + db.session.commit() + return make_response({"goal":new_goal.to_dict()}), 201 + + if request.method == "GET": + goals_list = Goal.query.all() + response = [] + for my_goal in goals_list: + response.append(my_goal.to_dict()) + + return jsonify(response), 200 + +@goals_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def get_goal(goal_id): + goal_id = int(goal_id) + my_goal = Goal.query.get(goal_id) + if request.method == "GET": + if my_goal is None: + return "", 404 + else: + return make_response({"goal":my_goal.to_dict()}), 200 + + elif request.method == "PUT": + request_body = request.get_json() + try: + my_goal.title = request_body["title"] + db.session.commit() + return make_response({"goal":my_goal.to_dict()}), 200 + except AttributeError as ae: + return make_response("", 404) + + elif request.method == "DELETE": + if my_goal is None: + return "", 404 + else: + db.session.delete(my_goal) + db.session.commit() + myResponse = 'Goal ' + str(goal_id) + ' "' + my_goal.title + '" successfully deleted' + return make_response({"details":myResponse}), 200 + +@goals_bp.route("//tasks", methods=["GET", "POST"], strict_slashes=False) +def create_task_ids_to_goals(goal_id): + # goal_id = int(goal_id) + my_goal = Goal.query.get(goal_id) + if my_goal is None: + return "", 404 + request_body = request.get_json() + if request_body is not None: + task_ids = request_body['task_ids'] + else: + task_ids = [] + + if request.method == "POST": + #update all the tasks to point to the goal + listoftasks = [] + for taskid in task_ids: + mytask = Task.query.get(taskid) + mytask.goal_id = goal_id + listoftasks.append(taskid) + db.session.commit() + #return my_goal.goal_tasks_to_dict, 200 + #Query all the tasks with the goalID + # create your response here and not in the db.models + return make_response({"id":int(goal_id), "task_ids":listoftasks}), 200 + + if request.method == "GET": + #set up a list + listoftasks = [] + #Query all the tasks with the goalID + mytasks = Task.query.filter(Task.goal_id == goal_id) + for tasker in mytasks: + listoftasks.append(tasker.to_dict()) + #return my_goal.goal_tasks_to_dict, 200 + + # create your response here and not in the db.models + return make_response({"id":int(goal_id), "title":my_goal.title, "tasks":listoftasks}), 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/cf15913c78d7_.py b/migrations/versions/cf15913c78d7_.py new file mode 100644 index 000000000..444c3f8b8 --- /dev/null +++ b/migrations/versions/cf15913c78d7_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: cf15913c78d7 +Revises: +Create Date: 2021-11-04 09:32:40.779510 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'cf15913c78d7' +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.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.id'], ), + 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/tests/conftest.py b/tests/conftest.py index d11083bf3..d3d7b0755 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,8 +1,7 @@ import pytest -from app import create_app +from app import create_app, db from app.models.task import Task from app.models.goal import Goal -from app import db from datetime import datetime diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index cc6459a12..401a675d2 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -28,7 +28,6 @@ def test_get_tasks_one_saved_tasks(client, one_task): } ] - def test_get_task(client, one_task): # Act response = client.get("/tasks/1") diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 6ba60c6fa..e61a33c70 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,18 +42,15 @@ 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() # 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 +69,40 @@ 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): - 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") +#@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("/goals/1", json={ + "title": "Updated Goal Title", + }) + 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 +121,16 @@ 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") +#@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): diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 48ecd0523..4a7f2e662 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -1,6 +1,5 @@ from app.models.goal import Goal - def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={