diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..a6469d387 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,10 @@ +import pytest from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate import os from dotenv import load_dotenv +import datetime db = SQLAlchemy() @@ -12,6 +14,7 @@ def create_app(test_config=None): app = Flask(__name__) + app.config['JSON_SORT_KEYS'] = False app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if test_config is None: @@ -21,14 +24,19 @@ def create_app(test_config=None): app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") + app.config['JSON_SORT_KEYS']=False + + db.init_app(app) + migrate.init_app(app, db) # Import models here for Alembic setup from app.models.task import Task from app.models.goal import Goal - db.init_app(app) - migrate.init_app(app, db) + from .routes import task_bp, goal_bp # Register Blueprints here + app.register_blueprint(task_bp) + app.register_blueprint(goal_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..f7ac674cc 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,33 @@ +from types import new_class from flask import current_app from app import db +from app.models.task import Task +# Parent Class class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + goal_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + tasks = db.relationship('Task', backref='goal', lazy=True) + + def goal_json_object(self): + return { + "id": self.goal_id, + "title": self.title + } + + def goal_json_object_with_tasks(self): + new_list = [] + for task in self.tasks: + new_list.append({ + "id": task.id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at_helper() + }) + return { + "id": self.goal_id, + "title": self.title, + "tasks": new_list + } diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..048dba037 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,32 @@ from flask import current_app from app import db - +from datetime import datetime +# this is telling flask about my database task table class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + 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) + + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) + def completed_at_helper(self): + if self.completed_at == None: + complete = False + else: + complete = True + return complete + + def json_object(self): + + new_reponse = { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": self.completed_at_helper() + } + if self.goal_id is not None: + new_reponse["goal_id"] = self.goal_id + return new_reponse + # Use this helper function any time the return is expected to be complete ^^^ + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..3d48bf3be 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,205 @@ -from flask import Blueprint +from app import db +from app.models.task import Task +from app.models.goal import Goal +from flask import request +from flask import request, Blueprint, make_response +from flask import jsonify +from datetime import datetime +from sqlalchemy import asc, desc +import requests +import json +import os +goal_bp = Blueprint("goals", __name__, url_prefix="/goals") +task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +#This is is a new endpoint. +@task_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def get_single_task(task_id): + task = Task.query.get(task_id) + + if task is None: + return jsonify(None), 404 + + complete = task.completed_at_helper() # Helper function to return boolean + + if request.method == "GET": + return jsonify({"task": task.json_object()}), 200 + + elif request.method == "PUT": + form_data = request.get_json() + + task.title = form_data["title"] + task.description = form_data["description"] + task.is_complete = form_data["completed_at"] + + db.session.commit() + return jsonify({"task": task.json_object()}),200 + + elif request.method == "DELETE": + db.session.delete(task) + db.session.commit() + return jsonify({"details": f'Task {task.id} "{task.title}" successfully deleted'}), 200 + +@task_bp.route("", methods=["GET", "POST"]) +def handle_tasks(): + if request.method == "GET": + + request_value = request.args.get("sort") + + if request_value == None: + tasks = Task.query.all() + + if request_value == "asc": + tasks = Task.query.order_by(Task.title.asc()) + + + if request_value == "desc": + tasks = Task.query.order_by(Task.title.desc()) + task_response = [] + + for task in tasks: + + task_response.append(task.json_object()) + + return jsonify(task_response), 200 + + elif request.method == "POST": + request_body = request.get_json() + + if "completed_at" not in request_body or "description" not in request_body or "title" not in request_body: + return jsonify({ + "details": "Invalid data" + }), 400 + + new_task = Task(title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"]) + + db.session.add(new_task) + db.session.commit() + + return jsonify({"task": new_task.json_object()}), 201 + + db.session.add(new_task) + db.session.commit() + +def slack_bot(task): + url = "https://slack.com/api/chat.postMessage?channel=task-notifications" + slack_token = os.environ.get("SLACK") + + payload = {"text": f"Someone just completed the task: '{task.title}'!"} + headers = {"Authorization": f"Bearer {slack_token}"} + + return requests.request("PATCH", url, headers=headers, data=payload) + + +@task_bp.route("//mark_complete", methods=["PATCH"], strict_slashes=False) +def mark_complete(task_id): + + if request.method == "PATCH": + + task = Task.query.get(task_id) + + if task is None: + return jsonify(None), 404 + + task.completed_at = datetime.now() + + + db.session.commit() + + # call slackbot + slack_bot(task) + + + return jsonify({"task": task.json_object()}),200 + + +@task_bp.route("//mark_incomplete", methods=["PATCH"], strict_slashes=False) +def mark_incomplete(task_id): + + if request.method == "PATCH": + + task = Task.query.get(task_id) + + if task is None: + return jsonify(None), 404 + + task.completed_at = None + + return jsonify({"task":task.json_object()}),200 + + +@goal_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def get_goal(goal_id): + + goal = Goal.query.get(goal_id) + + if goal is None: + return jsonify(None), 404 + + if request.method == "GET": + return jsonify({"goal": goal.goal_json_object()}), 200 + + elif request.method == "PUT": + form_data = request.get_json() + #Go and get the data from the request + goal.title = form_data["title"] + + db.session.commit() + return jsonify({"goal": goal.goal_json_object()}),200 + + elif request.method == "DELETE": + db.session.delete(goal) + db.session.commit() + + return jsonify({"details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted'}), 200 + +@goal_bp.route("", methods=["POST", "GET"], strict_slashes=False) +def one_goal(): + if request.method == "GET": + goals = Goal.query.all() + + goal_response = [] + + for goal in goals: + goal_response.append(goal.goal_json_object()) + + return jsonify(goal_response), 200 + + if request.method == "POST": + request_body = request.get_json() + + if request_body == {}: + return jsonify({"details": f'Invalid data'}), 400 + + new_goal = Goal(title=request_body["title"]) + + db.session.add(new_goal) + db.session.commit() + + return jsonify({"goal":new_goal.goal_json_object()}),201 + +#New endpoint to look up goals and task +@goal_bp.route("//tasks", methods=["POST"], strict_slashes=False) +def goals_task(goal_id): + + form_data = request.get_json() + + for task_id in form_data["task_ids"]: + + task = Task.query.get(task_id) + + task.goal_id = goal_id + + db.session.commit() + + return make_response({"id": int(goal_id),"task_ids":form_data["task_ids"]}), 200 + +@goal_bp.route("//tasks", methods=["GET"], strict_slashes=False) +def goals_task_get(goal_id): + if request.method == "GET": + goal = Goal.query.get(goal_id) + if goal is None: + return make_response("", 404) + return jsonify(goal.goal_json_object_with_tasks()) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/594ba04b1737_.py b/migrations/versions/594ba04b1737_.py new file mode 100644 index 000000000..4e8f01e8f --- /dev/null +++ b/migrations/versions/594ba04b1737_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: 594ba04b1737 +Revises: +Create Date: 2021-05-13 00:13:03.256590 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '594ba04b1737' +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(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('goal_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=False), + sa.ForeignKeyConstraint(['goal_id'], ['goal.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/requirements.txt b/requirements.txt index cfdf74050..ffcfcb2eb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -29,4 +29,4 @@ six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 urllib3==1.26.4 -Werkzeug==1.0.1 +Werkzeug==1.0.1 \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fb943d9b3..b9b401238 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -69,7 +69,7 @@ def test_create_task_with_none_completed_at(client): # Assert assert response.status_code == 201 assert "task" in response_body - assert response_body == { + assert response_body == { "task": { "id": 1, "title": "A Brand New Task",