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..a50705cc1 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from flask_cors import CORS import os from dotenv import load_dotenv @@ -27,8 +28,17 @@ def create_app(test_config=None): from app.models.goal import Goal db.init_app(app) + CORS(app) migrate.init_app(app, db) + + # Register Blueprints here + from .routes import task_list_bp, goal_list_bp + app.register_blueprint(task_list_bp) + app.register_blueprint(goal_list_bp) + + + return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..619623c4b 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,4 +3,16 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + goal_id = db.Column(db.Integer, autoincrement=True, primary_key=True) + title = db.Column(db.String, nullable = False) + tasks = db.relationship( + 'Task', backref='goal', lazy=True + ) + # task_id = db.Column(db.Integer, autoincrement=True, primary_key=True) + + def serialize(self): + result = { + 'id': self.goal_id, + 'title': self.title + } + return result diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..a52c84818 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,53 @@ from flask import current_app +from requests.models import parse_header_links from app import db +import requests +import os class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + task_id = db.Column(db.Integer, autoincrement=True, 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 serialize(self): + result = { + 'id': self.task_id, + 'title': self.title, + 'description': self.description, + 'is_complete': self.completed_at != None + } + if self.goal_id: + result['goal_id'] = self.goal_id + return result + + # def serialize_two(self): + # result = { + # 'id': self.task_id, + # 'goal_id': self.goal_id, + # 'title': self.title, + # 'description': self.description, + # 'is_complete': self.completed_at != None + # } + # return result + + def notify_slack(self): + message = f"Someone just completed the task {self.title}" + url = "https://slack.com/api/chat.postMessage" + params = { + + "channel":"task-notifications", + "text": message + } + headers = { + "Authorization": os.environ.get('SLACK_API') + } + r = requests.post(url, data = params, headers = headers) + r.status_code + + + + + diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..43e93b9ad 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,266 @@ +from flask_sqlalchemy.model import camel_to_snake_case +from tests.test_wave_01 import test_create_task_must_contain_description from flask import Blueprint +from app import db +from app.models.task import Task +from app.models.goal import Goal +from flask import request, Blueprint, make_response, jsonify +from datetime import datetime +import requests + + +def order_by_title(task_response): + return task_response["title"] + +goal_list_bp = Blueprint("goal_list", __name__, url_prefix = '/goals') + +@goal_list_bp.route('', methods = ['GET','POST']) +def handle_goals(): + if request.method == 'GET': + goals = Goal.query.all() + goal_response = [] + for goal in goals: + goal_response.append(goal.serialize()) + return jsonify(goal_response) + + elif request.method == 'POST': + request_body = request.get_json() + if "title" in request_body: + new_goal = Goal( + title = request_body['title'] + ) + db.session.add(new_goal) + db.session.commit() + return{ + 'goal': + new_goal.serialize() + },201 + else: + return({ + "details": f'Invalid data' + },400) + +@goal_list_bp.route('/', methods = ['GET','PUT', 'DELETE']) +def handle_goal(goal_id): + goal = Goal.query.get(goal_id) + if not goal: + return "", 404 + + if request.method == 'GET': + #check expected output in test + return({ + 'goal': + goal.serialize() + + }) + elif request.method == 'PUT': + request_body = request.get_json() + if 'title' in request_body: + goal.title = request_body['title'] + db.session.commit() + return({ + 'goal': goal.serialize() + },200) + + elif request.method =='DELETE': + db.session.delete(goal) + db.session.commit() + return({ + "details": f'Goal {goal_id} "{goal.title}" successfully deleted' + },200) + +@goal_list_bp.route('//tasks', methods = ['GET']) +def get_tasks_for_goal(goal_id): + goal = Goal.query.get(goal_id) + if not goal: + return "", 404 + + tasks = goal.tasks + json_tasks = [] + for task in tasks: + serializeds_task = task.serialize() # dict + serializeds_task['goal_id'] = int(goal_id) + json_tasks.append(serializeds_task) + + + return { + "id": goal.goal_id, + "title": goal.title, + "tasks": json_tasks + }, 200 + +@goal_list_bp.route('//tasks', methods = ['POST']) +def add_task_to_goal(goal_id): + goal = Goal.query.get(goal_id) + tasks = request.json + tasks = tasks["task_ids"] + if not goal: + return "", 404 + # task = db.session.query(Task.id) + query = db.session.query(Task).filter(Task.task_id.in_(tasks)) + + results = query.all() + for task in results: + task.goal_id = goal.goal_id + db.session.commit() + + return{ + 'id': goal.goal_id, + 'task_ids': tasks + },200 + + + + + +task_list_bp = Blueprint("task_list", __name__, url_prefix='/tasks') +@task_list_bp.route('', methods=['GET', 'POST']) +def handle_tasks(): + if request.method == 'GET': + #return full list of tasks + + # allows access to keys - sort + arg = request.args # better name + if "sort" in arg: + if arg['sort'] == "asc": + tasks = Task.query.order_by(Task.title.asc()) + elif arg['sort'] == "desc": + tasks = Task.query.order_by(Task.title.desc()) + else: + tasks = Task.query.all() + task_response = [] + for task in tasks: + task_response.append(task.serialize()) + + return jsonify(task_response) + + elif request.method == 'POST': + request_body = request.get_json() + if "title" not in request_body: + return { + "details": "Invalid data" + }, 400 + elif "description" not in request_body: + return { + "details": "Invalid data" + }, 400 + elif "completed_at" not in request_body: + return { + "details": "Invalid data" + }, 400 + stringify_format = "%a, %d %b %Y %H:%M:%S %Z" + if request_body["completed_at"]: + + new_task = Task( + title = request_body['title'], + description = request_body['description'], + completed_at = datetime.strptime(request_body["completed_at"], stringify_format) + ) + else: + new_task = Task( + title = request_body['title'], + description = request_body['description'], + ) + db.session.add(new_task) + db.session.commit() + return{ + 'task':{ + 'id': new_task.task_id, + 'title': new_task.title, + 'description': new_task.description, + 'is_complete': new_task.completed_at != None + } + },201 + + +@task_list_bp.route('/', methods=['GET','PUT', 'DELETE']) +def handle_task(task_id): # same name as parameter route + task = Task.query.get(task_id) + if not task: + return "", 404 + + if request.method == 'GET': + return({ + 'task': task.serialize() + }) + elif request.method == 'DELETE': + db.session.delete(task) + db.session.commit() + return({ + "details": f'Task {task_id} "{task.title}" successfully deleted' + },200) + + + elif request.method =='PUT': + request_body = request.get_json() + if 'title' in request_body: + task.title = request_body['title'] + if 'description' in request_body: + task.description = request_body['description'] + if 'completed_at' in request_body: + task.completed = request_body['completed_at'] + if 'goal_id' in request_body: + task.goal_id= request_body['goal_id'] + db.session.commit() + return({ + 'task': task.serialize() + },200) + +@task_list_bp.route('//mark_complete',methods = ['PATCH']) +def mark_complete_task(task_id): + task = Task.query.get(task_id) + if not task: + return "Task not found", 404 + task.completed_at = datetime.utcnow() + task.notify_slack() + db.session.commit() + return{ + 'task':{ + 'id': task.task_id, + 'title': task.title, + 'description': task.description, + 'is_complete': task.completed_at != None + } + },200 +@task_list_bp.route('//mark_incomplete',methods = ['PATCH']) +def mark_incomplete_task(task_id): + task = Task.query.get(task_id) + if not task: + return "Task Not Found", 404 + task.completed_at = None + db.session.commit() + return{ + 'task':{ + 'id': task.task_id, + 'title': task.title, + 'description': task.description, + 'is_complete': task.completed_at != None + } + },200 + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/task-list-api.code-workspace b/app/task-list-api.code-workspace new file mode 100644 index 000000000..c7436621b --- /dev/null +++ b/app/task-list-api.code-workspace @@ -0,0 +1,11 @@ +{ + "folders": [ + { + "path": ".." + }, + { + "path": "../../api/solar-system-api" + } + ], + "settings": {} +} \ 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/51918445a19e_.py b/migrations/versions/51918445a19e_.py new file mode 100644 index 000000000..8966ccc9f --- /dev/null +++ b/migrations/versions/51918445a19e_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: 51918445a19e +Revises: +Create Date: 2021-05-25 17:45:04.997629 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '51918445a19e' +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=False), + 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 ### diff --git a/requirements.txt b/requirements.txt index cfdf74050..eac2ec627 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,7 @@ certifi==2020.12.5 chardet==4.0.0 click==7.1.2 Flask==1.1.2 +flask-cors Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 gunicorn==20.1.0 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fb943d9b3..55e43b366 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -59,11 +59,13 @@ def test_get_task_not_found(client): def test_create_task_with_none_completed_at(client): # Act - response = client.post("/tasks", json={ + + request_body = { "title": "A Brand New Task", "description": "Test Description", "completed_at": None - }) + } + response = client.post("/tasks", json = request_body) response_body = response.get_json() # Assert diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 48ecd0523..e8aa19417 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -54,6 +54,9 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): response = client.get("/goals/1/tasks") response_body = response.get_json() + # package = amazon_website.buy("socks") + # package_contents = package.get_json() + # Assert assert response.status_code == 200 assert "tasks" in response_body