diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..6730bb663 --- /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..96eb32093 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,12 +15,10 @@ def create_app(test_config=None): app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if test_config is None: - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["TESTING"] = True - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_TEST_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") # Import models here for Alembic setup from app.models.task import Task @@ -30,5 +28,9 @@ def create_app(test_config=None): 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) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..e777f1fe7 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,14 @@ 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) + title = db.Column(db.String) + +def to_json(self): + return { + "id": self.goal_id, + "title": self.title, + } + diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..d50b991f9 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,40 @@ -from flask import current_app +from flask import request, current_app from app import db +# from app.models.goal import Goal class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + 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.goal_id"), nullable=True) + goal = db.relationship("Goal", backref=db.backref("tasks"), lazy=True) + +def to_dict(self): + return { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": bool(self.completed_at) + } + +def to_dict_goal(self): + return { + "id": self.task_id, + "goal_id": self.goal_id, + "title": self.title, + "description": self.description, + "is_complete": bool(self.completed_at) + } + + +# def completed_task(self): +# if self.completed_at == None: +# completed = False +# else: +# completed = True + + + + diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..18e4d9cda 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,263 @@ -from flask import Blueprint +from flask.wrappers import Response +from app import db +from app.models.task import Task, to_dict, to_dict_goal +from app.models.goal import Goal, to_json +from flask import Blueprint, request, make_response, jsonify +from datetime import datetime +from dotenv import load_dotenv +import os +import requests + +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") +load_dotenv() + +# tasks + +@tasks_bp.route("", methods=["POST"], strict_slashes=False) +def create_task(): + + request_body = request.get_json() + + response = {"details": "Invalid data"} + + if "title" not in request_body.keys() or "description" not in request_body.keys() or "completed_at" not in request_body.keys(): + + return jsonify(response), 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() + valid_task = {"task": to_dict(new_task)} + + return jsonify(valid_task), 201 + + +@tasks_bp.route("", methods=["GET"], strict_slashes=False) +def get_tasks(): + + tasks_response = [] + + sort_query = request.args.get("sort") + + if sort_query == "asc": + tasks = Task.query.order_by(Task.title.asc()) + + elif sort_query == "desc": + tasks = Task.query.order_by(Task.title.desc()) + + else: + tasks = Task.query.all() + + for task in tasks: + tasks_response.append(to_dict(task)) + + return jsonify(tasks_response), 200 + + +@tasks_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def handle_task(task_id): + + task = Task.query.get(task_id) + + if request.method == "GET": + if task is None: + return make_response(f"404 Not Found", 404) + + else: + one_task = to_dict(task) + + return {"task": one_task} + + + elif request.method == "PUT": + if task: + 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() + + updated_task = { + "id": task.task_id, + "title": task.title, + "description": task.description, + "is_complete": bool(task.completed_at) + } + else: + return make_response(f"", 404) + + return {'task': updated_task} + + elif request.method == "DELETE": + if task: + db.session.delete(task) + db.session.commit() + + response = {"details": f"Task {task.task_id} \"{task.title}\" successfully deleted"} + + return jsonify(response), 200 + + else: + return make_response(f"", 404) + + +@tasks_bp.route("//mark_complete", methods=["PATCH"], strict_slashes=False) +def mark_complete(task_id): + + task = Task.query.get(task_id) + + if task is None: + return jsonify(None), 404 + + task.completed_at = datetime.utcnow() + db.session.commit() + + slack_bot_notification("Did this work") + + return jsonify({"task": to_dict(task)}), 200 + +def slack_bot_notification(message): + path = "https://slack.com/api/chat.postMessage" + SLACK_KEY = os.environ.get("SLACK_TOKEN") + headers = {"Authorization": f"Bearer {SLACK_KEY}"} + query_params = {"channel": "task-notifications", "text": message} + requests.post(path, params=query_params, headers=headers) + + +@tasks_bp.route("/mark_incomplete", methods=["PATCH"], strict_slashes=False) +def mark_incomplete(task_id): + + task = Task.query.get(task_id) + + if task is None: + return jsonify(None), 404 + + task.completed_at = None + db.session.commit() + + return jsonify({"task": to_dict(task)}), 200 + + +# goals + +@goals_bp.route("", methods=["POST"], strict_slashes=False) +def create_goal(): + + request_body = request.get_json() + + response = {"details": "Invalid data"} + + if "title" not in request_body.keys(): + + return jsonify(response), 400 + + else: + new_goal = Goal(title = request_body["title"]) + db.session.add(new_goal) + db.session.commit() + valid_goal = {"goal": to_json(new_goal)} + + return jsonify(valid_goal), 201 + +@goals_bp.route("", methods=["GET"], strict_slashes=False) +def get_goals(): + + goals = Goal.query.all() + goals_response = [] + + if goals != None: + + for goal in goals: + goals_response.append(to_json(goal)) + + return jsonify(goals_response), 200 + + return jsonify(goals_response), 200 + + +@goals_bp.route("/", methods=["GET", "PUT", "DELETE"], strict_slashes=False) +def handle_goal(goal_id): + + goal = Goal.query.get(goal_id) + + if request.method == "GET": + if goal is None: + return make_response("", 404) + + else: + valid_goal = {"goal": to_json(goal)} + + return jsonify(valid_goal), 200 + + elif request.method == "PUT": + if goal: + form_data = request.get_json() + goal.title = form_data["title"] + db.session.commit() + + updated_goal = { + "id": goal.goal_id, + "title": goal.title + } + + else: + return make_response("", 404) + + return {'goal': updated_goal} + + elif request.method == "DELETE": + if goal: + db.session.delete(goal) + db.session.commit() + + response = {"details": f"Goal {goal.goal_id} \"{goal.title}\" successfully deleted"} + + return jsonify(response), 200 + + else: + return make_response(f"", 404) + + +@goals_bp.route("//tasks", methods=["POST", "GET"], strict_slashes=False) +def goal_task_relationship(goal_id): + + goal = Goal.query.get(goal_id) + + request_body = request.get_json() + + if request.method == "POST": + + task_ids = request_body["task_ids"] + + for task_id in task_ids: + task = Task.query.get(task_id) + task.goal_id = goal_id # or goal.tasks.append(task) + + db.session.commit() + + return {"id": int(goal_id), "task_ids": task_ids}, 200 + + elif request.method == "GET": + + # tasks_list = [] + + if goal: + tasks = goal.tasks + + # for task in tasks: + # tasks_list.append(to_dict_goal(task)) + + task_list = [to_dict_goal(task) for task in tasks] + + return { + "id": goal.goal_id, + "title": goal.title, + "tasks": task_list + }, 200 + + else: + return make_response("", 404) + 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/90c15be06d65_.py b/migrations/versions/90c15be06d65_.py new file mode 100644 index 000000000..e7d5d080a --- /dev/null +++ b/migrations/versions/90c15be06d65_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: 90c15be06d65 +Revises: +Create Date: 2021-05-12 22:24:33.196689 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '90c15be06d65' +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.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_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.goal_id'], ), + 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 ###