Skip to content

Zoisite - L. Pollard #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,30 @@ 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")
"RENDER_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")
"RENDER_DATABASE_URI")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just something small to point out here. Lines 20 and 26 are currently the exact same which means that the line itself could be pulled out of the conditional entirely. This wasn't an issue before when you were differentiating between the testing and the development database, but now that it has all been updated to the Render database, we have that collision.


# 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)

# Import models here for Alembic setup
from app.models.task import Task
from app.models.goal import Goal

# Register Blueprints here
from .task_routes import task_bp
app.register_blueprint(task_bp)

from .goal_routes import goal_bp
app.register_blueprint(goal_bp)

return app

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love what you have done organizationally in terms of separating out the goal_routes from the task_routes. One small tweak would be to make a new directory called "routes" to house those two files along with your helper.py.

Also, don't forget that if you do that, you will need an empty init.py file inside the routes directory. You also will need an empty init.py file inside your models directory!

108 changes: 108 additions & 0 deletions app/goal_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
from app import db
from flask import Blueprint, jsonify, abort, make_response, request
from app.models.goal import Goal
from app.models.task import Task
import datetime
import requests
import os

goal_bp = Blueprint("goals", __name__, url_prefix="/goals")


def validate_model(cls, model_id):
try:
model_id = int(model_id)
except:
abort(make_response(
jsonify({"message": f"{cls.__name__} {model_id} invalid"}), 400))

model = cls.query.get(model_id)
if not model:
abort(make_response(
jsonify({"message": f"{cls.__name__} {model_id} not found"}), 404))

return model

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job making the validate model method class agnostic!



@goal_bp.route("", methods=["POST"])
def create_goal():
request_body = request.get_json()

try:
request_body["title"]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love the idea to include some error handling here. We unfortunately cannot simply try to see if the request body exists. Instead, lines 36-43 should be included in the try with line 32 removed!

except:
abort(make_response(jsonify({"details": "Invalid data"}), 400))

new_goal = Goal.from_dict(request_body)

db.session.add(new_goal)
db.session.commit()

response_body = {"goal": new_goal.to_dict()}

return make_response(jsonify(response_body), 201)


@goal_bp.route("", methods=["GET"])
def get_goals():
goals = Goal.query.all()
results = [goal.to_dict() for goal in goals]

return jsonify(results)


@goal_bp.route("/<goal_id>", methods=["GET"])
def get_one_goal(goal_id):
goal = validate_model(Goal, goal_id)
response_body = {"goal": goal.to_dict()}

return response_body


@goal_bp.route("/<goal_id>", methods=["PUT"])
def update_goal(goal_id):
goal = validate_model(Goal, goal_id)
goal_updates = request.get_json()
goal.title = goal_updates["title"]
response_body = {"goal": goal.to_dict()}
db.session.commit()

return response_body


@goal_bp.route("/<goal_id>", methods=["DELETE"])
def delete_goal(goal_id):
goal_to_delete = validate_model(Goal, goal_id)
db.session.delete(goal_to_delete)
db.session.commit()
response_body = {
"details": f'Goal {goal_to_delete.goal_id} "{goal_to_delete.title}" successfully deleted'}

return make_response(jsonify(response_body))


@goal_bp.route("/<goal_id>/tasks", methods=["POST"])
def post_task_to_goal(goal_id):
goal = validate_model(Goal, goal_id)
request_body = request.get_json()
for task_id in request_body["task_ids"]:
task = validate_model(Task, task_id)
task.goal_id = goal.goal_id
db.session.commit()
task_id_list = []
for task in goal.tasks:
task_id_list.append(task.task_id)

response_body = {
"id": goal.goal_id,
"task_ids": task_id_list
}
return make_response(jsonify(response_body))


@goal_bp.route("/<goal_id>/tasks", methods=["GET"])
def get_tasks_of_goal(goal_id):
goal = validate_model(Goal, goal_id)
response_body = goal.to_dict(tasks=True)

return make_response(jsonify(response_body))
24 changes: 24 additions & 0 deletions app/models/goal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,27 @@

class Goal(db.Model):
goal_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
tasks = db.relationship("Task", back_populates="goal", lazy=True)


def to_dict(self, tasks=False):
goal_dict = {
"id": self.goal_id,
"title": self.title

}
if tasks:
goal_dict["tasks"]= [task.to_dict() for task in self.tasks]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great list comprehension here!


return goal_dict




@classmethod
def from_dict(cls, goal_data):
return Goal(
title=goal_data["title"]
)

27 changes: 26 additions & 1 deletion app/models/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,29 @@


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, nullable=False)
description = db.Column(db.String, nullable=False)
completed_at = db.Column(db.DateTime, nullable=True, default=None)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This all looks good! One small note is that the default for the nullable attribute is True, so it doesn't need to be explicitly stated here!

goal_id = db.Column(db.Integer, db.ForeignKey(
'goal.goal_id'), nullable=True)
goal = db.relationship("Goal", back_populates="tasks")

def to_dict(self):
task_dict = {
"id": self.task_id,
"title": self.title,
"description": self.description,
"is_complete": bool(self.completed_at)
}
if self.goal_id:
task_dict["goal_id"] = self.goal_id

return task_dict

@classmethod
def from_dict(cls, task_data):
return Task(
title=task_data["title"],
description=task_data["description"]
)
1 change: 0 additions & 1 deletion app/routes.py

This file was deleted.

116 changes: 116 additions & 0 deletions app/task_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
from app import db
from app.models.task import Task
from flask import Blueprint, jsonify, abort, make_response, request
import datetime, requests, os

task_bp = Blueprint("tasks", __name__, url_prefix="/tasks")

def validate_model(cls, model_id):
try:
model_id = int(model_id)
except:
abort(make_response(jsonify({"message":f"{cls.__name__} {model_id} invalid"}), 400))

model = cls.query.get(model_id)
if not model:
abort(make_response(jsonify({"message":f"{cls.__name__} {model_id} not found"}), 404))

return model

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job with this validate model method!



@task_bp.route("", methods=["POST"])
def create_task():
request_body = request.get_json()

try:
request_body["title"] and request_body["description"]
except:
abort(make_response(jsonify({"details":"Invalid data"}), 400))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great attempt at error handling. Just a reminder however that lines 30-37 should be included in the try block here. The code on line 26 won't actually do anything besides returning true or false. A more appropriate approach might look like the following:

 try:
    new_task = Task.from_dict(request_body)

    db.session.add(new_task)
    db.session.commit()

    return make_response(jsonify({"task": new_task.to_dict()}), 201)

new_task = Task.from_dict(request_body)

db.session.add(new_task)
db.session.commit()

response_body = {"task":new_task.to_dict()}

return make_response(jsonify(response_body), 201)


@task_bp.route("", methods=["GET"])
def get_task():
sort_query = request.args.get("sort")
if sort_query == "asc":
tasks = Task.query.order_by(Task.title).all()
elif sort_query == "desc":
tasks = Task.query.order_by(Task.title.desc()).all()

else:
tasks = Task.query.all()
results = [task.to_dict() for task in tasks]

return jsonify(results)


@task_bp.route("/<task_id>", methods=["GET"])
def get_one_task(task_id):
task = validate_model(Task, task_id)
response_body = {"task":task.to_dict()}

return response_body


@task_bp.route("/<task_id>", methods=["PUT"])
def update_task(task_id):
task = validate_model(Task, task_id)
task_updates = request.get_json()
task.title = task_updates["title"]
task.description = task_updates["description"]
response_body = {"task":task.to_dict()}
db.session.commit()

return response_body

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The put method could also use some error handling in case the necessary update attributes are not included in the request!


@task_bp.route("/<task_id>", methods=["DELETE"])
def delete_task(task_id):
task_to_delete = validate_model(Task, task_id)
db.session.delete(task_to_delete)
db.session.commit()
response_body = {"details": f'Task {task_to_delete.task_id} "{task_to_delete.title}" successfully deleted'}


return make_response(jsonify(response_body))

@task_bp.route("/<task_id>/mark_complete", methods=["PATCH"])
def mark_task_complete(task_id):
task = validate_model(Task, task_id)

task.completed_at = datetime.datetime.now()

response_body = {"task": task.to_dict()}
db.session.commit()

path = "https://slack.com/api/chat.postMessage"
api_key = os.environ.get("SLACKBOT_API_TOKEN")
headers = {
"authorization": f"Bearer {api_key}"
}

data = {
"channel": "C0572HAGWUX",
"text": f"Someone just completed the task {task.title}"
}
requests.post(path, headers=headers, data=data)

return response_body

@task_bp.route("/<task_id>/mark_incomplete", methods=["PATCH"])
def mark_task_incomplete(task_id):
task = validate_model(Task, task_id)

task.completed_at = None

response_body = {"task": task.to_dict()}
db.session.commit()

return response_body
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -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
Loading