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..88bc53503 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,23 +4,21 @@ 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 + 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['TESTING'] = True + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + 'SQLALCHEMY_TEST_DATABASE_URI') # Import models here for Alembic setup from app.models.task import Task @@ -28,7 +26,13 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) + load_dotenv() # Register Blueprints here + from .routes import tasks_bp + app.register_blueprint(tasks_bp) + from .routes import goals_bp + app.register_blueprint(goals_bp) + return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..945adcb0a 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,14 @@ from flask import current_app +from sqlalchemy.orm import backref from app import db - 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='goaltask', lazy=True) + + def goal_json(self): + return { + "id": self.goal_id, + "title": self.title + } diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..27b2415c4 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,30 @@ from flask import current_app from app import db - +from sqlalchemy import DateTime +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) + goaltask_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) + + # creates a dictionary of key-value pairs describing the given task + def to_json(self): + # Wave 6: need to create a conditional for "goal_id" + if self.goaltask_id == None: + return { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": False if self.completed_at is None else True + } + else: + return{ + "id": self.task_id, + "goal_id": self.goaltask_id, + "title": self.title, + "description": self.description, + "is_complete": False if self.completed_at is None else True + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..bb355c746 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,328 @@ -from flask import Blueprint +from flask import Blueprint, request, jsonify +from werkzeug.wrappers import PlainRequest +from app import db +from flask.helpers import make_response +from app.models.task import Task +from app.models.goal import Goal +from datetime import date +import os +import requests +# sets up blueprints - with details +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + +# +# Wave 1: GET & POST functions - gets data for all tasks in table, and creates new tasks +# come back and refactor into task_index & independent POST function +@tasks_bp.route("", methods=["GET","POST"], strict_slashes=False) +def handle_tasks(): + if request.method == "GET": + task_title_from_url = request.args.get("title") + # search for task by title + if task_title_from_url: + tasks = Task.query.filter_by(title=task_title_from_url) + # all tasks + else: + tasks = Task.query.all() + + tasks_response = [] + + for task in tasks: + tasks_response.append(task.to_json()) + + # Wave 2 ascending/descending logic for GET method + if "asc" in request.full_path: + sorted_ascending = sorted(tasks_response, key=lambda x: x.get("title")) + return jsonify(sorted_ascending) + + elif "desc" in request.full_path: + sorted_descending = sorted(tasks_response, key=lambda x: x.get("title"), reverse=True) + return jsonify(sorted_descending) + + return jsonify(tasks_response), 200 + + elif request.method == "POST": + # try and except block for KeyError + try: + request_body = request.get_json() + + 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 { + "task": new_task.to_json() + }, 201 + + except KeyError: + return{"details": "Invalid data"}, 400 + +# helper function that will eventually check for task_ids being integers +def is_int(value): + try: + return int(value) + except ValueError: + return False + +# GET function - gets the data for the task with the specified task_id +@tasks_bp.route("/", methods=["GET"], strict_slashes=False) +def get_one_task(task_id): + if not is_int(task_id): + return{ + "message": f"ID {task_id} must be an integer", + "success": False + }, 400 + + task = Task.query.get(task_id) + + if task is None: + return make_response("", 404) + else: + return { + "task": task.to_json() + }, 200 +# PUT function - Updates either/or both title & description data +# for specified task (via task_id) +@tasks_bp.route("/", methods=["PUT"], strict_slashes=False) +def update_task(task_id): + + task = Task.query.get(task_id) + + if task: + task_data = request.get_json() + + task.title = task_data["title"] + task.description = task_data["description"] + + db.session.commit() + + return{ + "task": task.to_json() + }, 200 + else: + return make_response("", 404) + +# DELETE function - deletes specified task (via task_id) +@tasks_bp.route("/", methods=["DELETE"], strict_slashes=False) +def delete_task(task_id): + + task = Task.query.get(task_id) + + if task is None: + return make_response("", 404) + else: + db.session.delete(task) + db.session.commit() + + return { + "details": f'Task {task.task_id} "{task.title}" successfully deleted' + } + +# PATCH function - mark complete (includes call_slack_bot helper funciton) +@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 make_response("", 404) + else: + task.completed_at = date.today() + db.session.commit() + + call_slack_bot(task) + + return{ + "task": task.to_json() + }, 200 + +# PATCH function - mark_incomplete +@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 make_response("", 404) + else: + task.completed_at = None + db.session.commit() + + return { + "task": task.to_json() + }, 200 + +# Wave 4: separate function that sends a POST request to the slack bot +def call_slack_bot(task): + SLACK_API_TOKEN = os.environ.get('BOT_API_TOKEN') + url = "https://slack.com/api/chat.postMessage" + payload = { + "channel": "task-notifications", + "text": f"Someone just completed the task {task.title}" + } + headers = { + "Authorization": f"Bearer {SLACK_API_TOKEN}", + } + return requests.request("POST", url, data=payload, headers=headers) + +# wave 5 goal routes +# refactor into separate GET & POST functions +@goals_bp.route("", methods=["GET","POST"], strict_slashes=False) +def handle_goals(): + if request.method == "GET": + goal_title_from_url = request.args.get("title") + # search for goal by title + if goal_title_from_url: + goals = Goal.query.filter_by(title=goal_title_from_url) + # all goals + else: + goals = Goal.query.all() + + goals_response = [] + + for goal in goals: + goals_response.append(goal.goal_json()) + + # implements Wave 2 ascending/descending sort logic + if "asc" in request.full_path: + sorted_ascending = sorted(goals_response, key=lambda x: x.get("title")) + return jsonify(sorted_ascending) + + elif "desc" in request.full_path: + sorted_descending = sorted(goals_response, key=lambda x: x.get("title"), reverse=True) + return jsonify(sorted_descending) + + return jsonify(goals_response), 200 + + elif request.method == "POST": + # try and except block for KeyError + try: + request_body = request.get_json() + + new_goal = Goal(title=request_body["title"]) + + db.session.add(new_goal) + db.session.commit() + + return { + "goal": new_goal.goal_json() + }, 201 + + except KeyError: + return{"details": "Invalid data"}, 400 + +def is_int(value): + try: + return int(value) + except ValueError: + return False + +# Handles GET requests for 1 method with the provided goal id. +@goals_bp.route("/", methods=["GET"], strict_slashes=False) +def get_one_goal(goal_id): + if not is_int(goal_id): + return{ + "message": f"ID {goal_id} must be an integer", + "success": False + }, 400 + + goal = Goal.query.get(goal_id) + + if goal is None: + return make_response("", 404) + else: + return { + "goal": goal.goal_json() + }, 200 + +@goals_bp.route("/", methods=["PUT"], strict_slashes=False) +def update_goal(goal_id): + + goal = Goal.query.get(goal_id) + + if goal: + goal_data = request.get_json() + + goal.title = goal_data["title"] + + db.session.commit() + + return{ + "goal": goal.goal_json() + }, 200 + else: + return make_response("", 404) + +@goals_bp.route("/", methods=["DELETE"], strict_slashes=False) +def delete_goal(goal_id): + + goal = Goal.query.get(goal_id) + + if goal is None: + return make_response("", 404) + else: + db.session.delete(goal) + db.session.commit() + + return { + "details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted' + } +# wave 6 +# POST function: one(goal)-to-many(tasks) relationship +@goals_bp.route("//tasks", methods=["POST"], strict_slashes=False) +def post_goal_tasks(goal_id): + # gets the passed in information and gives it in json format + request_body = request.get_json() + # gets the goal that is associated with the given goal_id + goal = Goal.query.get(goal_id) + + # if no goal with the provided goal_id, returns a 404 error + if not goal: + return make_response("", 404) + else: + # iterates through the values for the "task_id" keys in request_body + for task_id in request_body["task_ids"]: + # in each iteration, gets the task that corresponds to the current task_id + task = Task.query.get(task_id) + # sets the value in the goaltask_id foreignkey column (in task table) to the corresponding goal_id + task.goaltask_id = goal_id + # commits the addition to the table to the database + db.session.commit() + # when a POST request is sent, return this in the response body + return { + "id": goal.goal_id, + "task_ids": request_body["task_ids"] + } + +# GET function: one(goal)-to-many(tasks) +@goals_bp.route("//tasks", methods=["GET"], strict_slashes=False) +def get_goal_tasks(goal_id): + goal = Goal.query.get(goal_id) + # sets task variable equal to the task with the corresponding goal (in foreignkey column) + task = Task.query.get(goal_id) + + # if goal doesn't exist, return a 404 error + if not goal: + return make_response("", 404) + else: + # sets outer dictionary (named response_dict) to dictionary created in Goal + response_dict = goal.goal_json() + # if there are no tasks associated with the goal, sets "tasks" equal to empty list + if task == None: + response_dict["tasks"] = [] + else: + # if task(s) associated with goal, return the task.json() + # data pulled from Task function + task_data_dict = task.to_json() + # sets response_dict "tasks" & task_data_dict "goal_id" values + + task_data_dict["goal_id"] = goal.goal_id + response_dict["tasks"] = [task_data_dict] + # commit changes to tables + db.session.commit() + return make_response(response_dict, 200) \ 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"}