From 92ca7b074d201e1e03c9d2e7d98675606f744dce Mon Sep 17 00:00:00 2001 From: mac-madison Date: Thu, 4 Nov 2021 18:23:21 -0700 Subject: [PATCH 1/6] had to create a new repo --- app/__init__.py | 9 +- app/models/goal.py | 15 ++- app/models/task.py | 22 +++- app/routes.py | 179 ++++++++++++++++++++++++++- migrations/README | 1 + migrations/alembic.ini | 45 +++++++ migrations/env.py | 96 ++++++++++++++ migrations/script.py.mako | 24 ++++ migrations/versions/4f3828955357_.py | 42 +++++++ 9 files changed, 428 insertions(+), 5 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/4f3828955357_.py diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..cab0caa04 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -16,19 +16,24 @@ def create_app(test_config=None): if test_config is None: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + "SQLALCHEMY_DATABASE_URI" + ) else: app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_TEST_DATABASE_URI") + "SQLALCHEMY_TEST_DATABASE_URI" + ) # Import models here for Alembic setup from app.models.task import Task from app.models.goal import Goal + from .routes import tasks_bp, goals_bp db.init_app(app) migrate.init_app(app, db) # Register Blueprints here + 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..a4ea2b1b2 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,4 +3,17 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + tasks = db.relationship("Task", back_populates="goal") + + def to_dict(self, has_tasks=False): + response = { + "id": self.id, + "title": self.title, + } + + if has_tasks: + response["tasks"] = [task.to_dict() for task in self.tasks] + + return response diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..f2191babd 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -3,4 +3,24 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, 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.id")) + goal = db.relationship("Goal", back_populates="tasks") + + def to_dict(self): + is_complete = False if not self.completed_at else True + + response = { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": is_complete, + } + + if self.goal: + response["goal_id"] = self.goal_id + return response diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..bc764d4b0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,179 @@ -from flask import Blueprint +"""Something went very, very wrong and I had to scrap my original repository, +start over and copy paste my code in. Hence, the lack of commits. +I was beginning the deployment stage and accidently deleted the origin remote. +This lead me down a very dark path, and ultimatly lead to me hitting the reset button +Anyways, +Since the functions for Goals and Tasks were so similar I experimented with having them share. +Not sure if this is a no no in real life, or if there is a better way to do it, let me know! +""" + +from flask import Blueprint, jsonify, request, abort, g +from app import db +from app.models.task import Task +from app.models.goal import Goal +from datetime import datetime +import os +import requests + +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + + +def slack_bot(text): + + SLACK_KEY = os.environ.get("SLACK_KEY") + req_body = {"channel": "task-notifications", "text": text} + headers = {"Authorization": f"Bearer {SLACK_KEY}"} + path = "https://slack.com/api/chat.postMessage" + + requests.post(path, json=req_body, headers=headers) + + +def validate(model, id): + + try: + id = int(id) + except: + abort(400, {"error": "invalid id"}) + return model.query.get_or_404(id) + + +@goals_bp.before_request +@tasks_bp.before_request +def get_model(): + + bps = {"tasks": (Task, "task"), "goals": (Goal, "goal")} + g.mod, g.name = bps[request.blueprint] + + +def sort(model): + + sort = request.args.get("sort") + if sort == "asc": + model = model.query.order_by(model.title.asc()) + elif sort == "desc": + model = model.query.order_by(model.title.desc()) + + return model + + +@goals_bp.route("", methods=["GET"]) +@tasks_bp.route("", methods=["GET"]) +def get_all(): + mod = g.mod + if "sort" in request.args: + mods = sort(mod) + else: + mods = mod.query.all() + + return jsonify([mod.to_dict() for mod in mods]) + + +@goals_bp.route("/", methods=["GET"]) +@tasks_bp.route("/", methods=["GET"]) +def get_one(id): + + mod, name = g.mod, g.name + mod = validate(mod, id) + + return {f"{name}": mod.to_dict()} + + +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +def mark_task_complete(id): + + task = validate(Task, id) + text = f"Someone just completed the task {task.title}" + slack_bot(text) + + task.completed_at = datetime.now() + db.session.commit() + + return {"task": task.to_dict()} + + +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_task_incomplete(id): + + task = validate(Task, id) + task.completed_at = None + db.session.commit() + + return {"task": task.to_dict()} + + +@goals_bp.route("/", methods=["DELETE"]) +@tasks_bp.route("/", methods=["DELETE"]) +def delete_one(id): + + mod, name = g.mod, g.name + mod = validate(mod, id) + + db.session.delete(mod) + db.session.commit() + + return { + "details": f'{name.capitalize()} {mod.id} "{mod.title}" successfully deleted' + } + + +@goals_bp.route("/", methods=["PUT"]) +@tasks_bp.route("/", methods=["PUT"]) +def update_one(id): + + mod, name = g.mod, g.name + mod = validate(mod, id) + request_body = request.get_json() + + mod.title = request_body["title"] + + if "description" in request_body: + mod.description = request_body["description"] + + db.session.commit() + return {f"{name}": mod.to_dict()} + + +@goals_bp.route("", methods=["POST"]) +@tasks_bp.route("", methods=["POST"]) +def create(): + mod, name = g.mod, g.name + request_body = request.get_json() + + try: + if mod == Task: + new_entry = mod( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"], + ) + elif mod == Goal: + new_entry = mod(title=request_body["title"]) + + except: + return {"details": "Invalid data"}, 400 + + db.session.add(new_entry) + db.session.commit() + + return {f"{name}": new_entry.to_dict()}, 201 + + +@goals_bp.route("//tasks", methods=["POST"]) +def add_tasks_to_goal(goal_id): + goal = validate(Goal, goal_id) + request_body = request.get_json() + + try: + goal.tasks = [validate(Task, task_id) for task_id in request_body["task_ids"]] + except: + return {"details": "Invalid data"}, 400 + + return {"id": goal.id, "task_ids": [task.id for task in goal.tasks]} + + +@goals_bp.route("//tasks", methods=["GET"]) +def get_tasks_by_goal(goal_id): + goal = validate(Goal, goal_id) + return goal.to_dict(has_tasks=True) 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/4f3828955357_.py b/migrations/versions/4f3828955357_.py new file mode 100644 index 000000000..22bcce1c5 --- /dev/null +++ b/migrations/versions/4f3828955357_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: 4f3828955357 +Revises: +Create Date: 2021-11-04 18:08:26.675826 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4f3828955357' +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(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), 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 ### From 949b63e8e758f6ace646fd5961cd35f1e578ff5c Mon Sep 17 00:00:00 2001 From: mac-madison Date: Thu, 4 Nov 2021 18:23:42 -0700 Subject: [PATCH 2/6] add routes to new repo --- app/routes.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index bc764d4b0..30861fd95 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,13 +1,3 @@ -"""Something went very, very wrong and I had to scrap my original repository, -start over and copy paste my code in. Hence, the lack of commits. -I was beginning the deployment stage and accidently deleted the origin remote. -This lead me down a very dark path, and ultimatly lead to me hitting the reset button - -Anyways, -Since the functions for Goals and Tasks were so similar I experimented with having them share. -Not sure if this is a no no in real life, or if there is a better way to do it, let me know! -""" - from flask import Blueprint, jsonify, request, abort, g from app import db from app.models.task import Task From 74abeb000435c1409e6c92eeecdea15d1aac61d4 Mon Sep 17 00:00:00 2001 From: mac-madison Date: Thu, 4 Nov 2021 20:31:30 -0700 Subject: [PATCH 3/6] add Procfile --- Procfile | 1 + 1 file changed, 1 insertion(+) create mode 100644 Procfile 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 From 6eedc80bd18ec784bc238accfd8d7b69a3526ae0 Mon Sep 17 00:00:00 2001 From: mac-madison Date: Fri, 5 Nov 2021 08:12:58 -0700 Subject: [PATCH 4/6] refactor for good looks --- app/models/goal.py | 5 ++ app/models/task.py | 5 ++ app/routes.py | 130 ++++++++++++++++++++++----------------------- 3 files changed, 74 insertions(+), 66 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index a4ea2b1b2..bcad04058 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -17,3 +17,8 @@ def to_dict(self, has_tasks=False): response["tasks"] = [task.to_dict() for task in self.tasks] return response + + def update(self, request_body): + for key, value in request_body.items(): + if key in Goal.__table__.columns.keys(): + setattr(self, key, value) diff --git a/app/models/task.py b/app/models/task.py index f2191babd..aa4fb65bf 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -24,3 +24,8 @@ def to_dict(self): if self.goal: response["goal_id"] = self.goal_id return response + + def update(self, request_body): + for key, value in request_body.items(): + if key in Task.__table__.columns.keys(): + setattr(self, key, value) diff --git a/app/routes.py b/app/routes.py index 30861fd95..38f434d1c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -3,8 +3,8 @@ from app.models.task import Task from app.models.goal import Goal from datetime import datetime -import os import requests +import os tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") goals_bp = Blueprint("goals", __name__, url_prefix="/goals") @@ -24,19 +24,11 @@ def validate(model, id): try: id = int(id) - except: - abort(400, {"error": "invalid id"}) + except ValueError: + abort(400) return model.query.get_or_404(id) -@goals_bp.before_request -@tasks_bp.before_request -def get_model(): - - bps = {"tasks": (Task, "task"), "goals": (Goal, "goal")} - g.mod, g.name = bps[request.blueprint] - - def sort(model): sort = request.args.get("sort") @@ -48,106 +40,112 @@ def sort(model): return model +@goals_bp.before_request +@tasks_bp.before_request +def get_model(): + + bps = {"tasks": (Task, "task"), "goals": (Goal, "goal")} + g.model, g.name = bps[request.blueprint] + + @goals_bp.route("", methods=["GET"]) @tasks_bp.route("", methods=["GET"]) def get_all(): - mod = g.mod + + model = g.model if "sort" in request.args: - mods = sort(mod) + models = sort(model) else: - mods = mod.query.all() + models = model.query.all() - return jsonify([mod.to_dict() for mod in mods]) + return jsonify([model.to_dict() for model in models]) @goals_bp.route("/", methods=["GET"]) @tasks_bp.route("/", methods=["GET"]) def get_one(id): - mod, name = g.mod, g.name - mod = validate(mod, id) + model, name = g.model, g.name + model = validate(model, id) - return {f"{name}": mod.to_dict()} + return {f"{name}": model.to_dict()} -@tasks_bp.route("//mark_complete", methods=["PATCH"]) -def mark_task_complete(id): +@goals_bp.route("", methods=["POST"]) +@tasks_bp.route("", methods=["POST"]) +def create(): + # put request bodies in models? + model, name = g.model, g.name + request_body = request.get_json() - task = validate(Task, id) - text = f"Someone just completed the task {task.title}" - slack_bot(text) + try: + if model == Task: + new_entry = model( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"], + ) + elif model == Goal: + new_entry = model(title=request_body["title"]) - task.completed_at = datetime.now() + except: + return {"details": "Invalid data"}, 400 + + db.session.add(new_entry) db.session.commit() - return {"task": task.to_dict()} + return {f"{name}": new_entry.to_dict()}, 201 -@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) -def mark_task_incomplete(id): +@goals_bp.route("/", methods=["PUT"]) +@tasks_bp.route("/", methods=["PUT"]) +def update_one(id): + model, name = g.model, g.name + model = validate(model, id) + request_body = request.get_json() - task = validate(Task, id) - task.completed_at = None - db.session.commit() + model.update(request_body) - return {"task": task.to_dict()} + db.session.commit() + return {f"{name}": model.to_dict()} @goals_bp.route("/", methods=["DELETE"]) @tasks_bp.route("/", methods=["DELETE"]) def delete_one(id): - mod, name = g.mod, g.name - mod = validate(mod, id) + model, name = g.model, g.name + model = validate(model, id) - db.session.delete(mod) + db.session.delete(model) db.session.commit() return { - "details": f'{name.capitalize()} {mod.id} "{mod.title}" successfully deleted' + "details": f'{name.capitalize()} {model.id} "{model.title}" successfully deleted' } -@goals_bp.route("/", methods=["PUT"]) -@tasks_bp.route("/", methods=["PUT"]) -def update_one(id): - - mod, name = g.mod, g.name - mod = validate(mod, id) - request_body = request.get_json() - - mod.title = request_body["title"] +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +def mark_task_complete(id): - if "description" in request_body: - mod.description = request_body["description"] + task = validate(Task, id) + text = f"Someone just completed the task {task.title}" + slack_bot(text) + task.completed_at = datetime.now() db.session.commit() - return {f"{name}": mod.to_dict()} + return {"task": task.to_dict()} -@goals_bp.route("", methods=["POST"]) -@tasks_bp.route("", methods=["POST"]) -def create(): - mod, name = g.mod, g.name - request_body = request.get_json() - - try: - if mod == Task: - new_entry = mod( - title=request_body["title"], - description=request_body["description"], - completed_at=request_body["completed_at"], - ) - elif mod == Goal: - new_entry = mod(title=request_body["title"]) - except: - return {"details": "Invalid data"}, 400 +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_task_incomplete(id): - db.session.add(new_entry) + task = validate(Task, id) + task.completed_at = None db.session.commit() - return {f"{name}": new_entry.to_dict()}, 201 + return {"task": task.to_dict()} @goals_bp.route("//tasks", methods=["POST"]) From 0bffd654d1c0bd92bf32bd61d630925417c87bc3 Mon Sep 17 00:00:00 2001 From: mac-madison Date: Fri, 5 Nov 2021 08:16:22 -0700 Subject: [PATCH 5/6] refactor for good looks --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 38f434d1c..f48905128 100644 --- a/app/routes.py +++ b/app/routes.py @@ -74,7 +74,7 @@ def get_one(id): @goals_bp.route("", methods=["POST"]) @tasks_bp.route("", methods=["POST"]) def create(): - # put request bodies in models? + model, name = g.model, g.name request_body = request.get_json() From f2538d7d29fb5c8ebf0a381a0c5161cf45856d2f Mon Sep 17 00:00:00 2001 From: mac-madison Date: Fri, 5 Nov 2021 08:34:33 -0700 Subject: [PATCH 6/6] FIN --- app/routes.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/app/routes.py b/app/routes.py index f48905128..b254626ec 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,3 +1,18 @@ +""" +Something went very, very wrong and I had to scrap my original repository, +start over and copy paste my code in. Hence, the lack of commits. +I was beginning the deployment stage and accidently deleted the origin remote. +This lead me down a very dark path, trying different git commands that I didnt fully understand. +It was chaos. + +Anyways, +I didn't have time to do docstrings. +Also, I experimented with doubling up the route decorators since the functions were +pretty much the same for Task & Goals. +Not sure if this is a no no in real life, or if there is a better way to do it. Let me know! +""" + + from flask import Blueprint, jsonify, request, abort, g from app import db from app.models.task import Task