Skip to content
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

Pine - Lety #70

Open
wants to merge 7 commits into
base: master
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
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn 'app:create_app()'
12 changes: 9 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@ def create_app(test_config=None):
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_TEST_DATABASE_URI")

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

# Register Blueprints here

from .routes import tasks_bp
from .routes import goals_bp

app.register_blueprint(tasks_bp)
app.register_blueprint(goals_bp)

from app.models.task import Task
from app.models.goal import Goal

return app
26 changes: 24 additions & 2 deletions app/models/goal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
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)
__tablename__ = 'goal'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String)
#these are not just IDs, like a list of numbers...they are objects of type Task

Choose a reason for hiding this comment

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

True!

tasks = db.relationship("Task", backref="goal", lazy=True)

def to_dict(self):
return {
"id": self.id,
"title": self.title,
}


def goal_tasks_to_dict(self):
mytasks = Task.query.all(self[0].tasks)
mylist = []
for thing in mytasks:
mylist.append(thing.id)

return {
"id": self.id,
"task_ids": mylist
}
Comment on lines +12 to +28

Choose a reason for hiding this comment

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

I feel like these could be combined.

20 changes: 19 additions & 1 deletion app/models/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,22 @@


class Task(db.Model):
task_id = db.Column(db.Integer, primary_key=True)
__tablename__ = '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.id"), nullable=True)

def to_dict(self):

Choose a reason for hiding this comment

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

👍 Nice helper method

result = {
"id": self.id,
"title": self.title,
"description": self.description,
"is_complete": True if self.completed_at else False
}

if self.goal_id:
result["goal_id"]=self.goal_id
return result

188 changes: 187 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,188 @@
from flask import Blueprint
from flask import Blueprint, jsonify, request, make_response
from flask.globals import session
from app import db
from app.models.task import Task
from app.models.goal import Goal
from sqlalchemy import asc, desc
from datetime import datetime
import requests
import urllib.parse
from dotenv import load_dotenv
import os

load_dotenv()

Choose a reason for hiding this comment

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

I think the load_dotenv() function has been run in the app/__init__.py file


tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks")
goals_bp = Blueprint("goals",__name__, url_prefix="/goals")

@tasks_bp.route("", methods=["POST","GET"], strict_slashes=False)
def create_task():
if request.method == "POST":
request_body = request.get_json()
if ("title" not in request_body) or ("description" not in request_body) or ("completed_at" not in request_body):
return {"details": "Invalid data"}, 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()
if request_body['completed_at'] == None:
return make_response({"task":new_task.to_dict()}), 201
else:
return make_response({"task":new_task.to_dict()}), 201
Comment on lines +28 to +31

Choose a reason for hiding this comment

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

I'm not sure what the point of this if-else block is?

elif request.method == "GET":
if "sort" in request.args:
title_sorter = request.args.get("sort")
if title_sorter == "asc":
tasks_list = Task.query.order_by(Task.title.asc()).all()
elif title_sorter == "desc":
tasks_list = Task.query.order_by(Task.title.desc()).all()
else:
tasks_list = Task.query.all()
response = []
for my_task in tasks_list:
response.append(my_task.to_dict())
return jsonify(response), 200

@tasks_bp.route("/<task_id>", methods=["GET", "PUT", "DELETE"], strict_slashes=False)
def get_task(task_id):
task_id = int(task_id)
my_task = Task.query.get(task_id)
if request.method == "GET":
if my_task is None:
return "", 404

Choose a reason for hiding this comment

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

This is mostly a chris-ism, but I prefer having a meaningful message in the response body in addition to responding with the response code.

else:
return make_response({"task":my_task.to_dict()}), 200

elif request.method == "PUT":
request_body = request.get_json()
try:
my_task.title = request_body["title"]
my_task.description = request_body["description"]
if "completed_at" in request_body :
my_task.completed_at = request_body["completed_at"]
db.session.commit()
return make_response({"task":my_task.to_dict()}), 200
except AttributeError as ae:
return make_response("", 404)

elif request.method == "DELETE":
if my_task is None:
return "", 404
else:
db.session.delete(my_task)
db.session.commit()
myResponse = 'Task ' + str(task_id) + ' "' + my_task.title + '" successfully deleted'
return make_response({"details":myResponse}), 200

@tasks_bp.route("/<task_id>/<completed_status>", methods=["PATCH"], strict_slashes=False )
def mark_complete(task_id, completed_status):
task_id = int(task_id)
my_task = Task.query.get(task_id)
if request.method == "PATCH":
if my_task is None:
return "", 404
else:
if completed_status == "mark_complete":
my_task.completed_at = datetime.now()
send_slack_notice(my_task.title)

Choose a reason for hiding this comment

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

I love the fact that you use a helper function here.

elif completed_status == "mark_incomplete":
my_task.completed_at = None
db.session.commit()
return make_response({"task" : my_task.to_dict()}), 200


def send_slack_notice(this_task_title):
#here we need to create an http.request to the slack end point
myNotice = urllib.parse.quote_plus("Someone just completed the task " + this_task_title)
my_url = "https://slack.com/api/chat.postMessage?channel=task-notifications&text=" + myNotice + "&pretty=1"
#add a request.header "Authorization", "super secret"
my_token = os.environ.get("MY_SLACK_TOKEN")
my_headers = {"Authorization": f"Bearer {my_token}"}
#send
r = requests.post(my_url, data="", headers=my_headers)

@goals_bp.route("", methods=["GET", "POST"], strict_slashes=False)
def create_goal():
if request.method == "POST":
request_body = request.get_json()
if "title" not in request_body:
return {"details": "Invalid data"}, 400

Choose a reason for hiding this comment

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

Maybe respond with more detail, like

Suggested change
return {"details": "Invalid data"}, 400
return {"details": "'title' is required"}, 400

else:
new_goal = Goal(title=request_body['title'])
db.session.add(new_goal)
db.session.commit()
return make_response({"goal":new_goal.to_dict()}), 201

if request.method == "GET":
goals_list = Goal.query.all()
response = []
for my_goal in goals_list:
response.append(my_goal.to_dict())

return jsonify(response), 200

@goals_bp.route("/<goal_id>", methods=["GET", "PUT", "DELETE"], strict_slashes=False)
def get_goal(goal_id):
goal_id = int(goal_id)
my_goal = Goal.query.get(goal_id)
if request.method == "GET":
if my_goal is None:
return "", 404
else:
return make_response({"goal":my_goal.to_dict()}), 200

elif request.method == "PUT":
request_body = request.get_json()
try:
my_goal.title = request_body["title"]
db.session.commit()
return make_response({"goal":my_goal.to_dict()}), 200
except AttributeError as ae:
return make_response("", 404)

elif request.method == "DELETE":
if my_goal is None:
return "", 404
else:
db.session.delete(my_goal)
db.session.commit()
myResponse = 'Goal ' + str(goal_id) + ' "' + my_goal.title + '" successfully deleted'
return make_response({"details":myResponse}), 200

@goals_bp.route("/<goal_id>/tasks", methods=["GET", "POST"], strict_slashes=False)
def create_task_ids_to_goals(goal_id):
# goal_id = int(goal_id)
my_goal = Goal.query.get(goal_id)
if my_goal is None:
return "", 404
request_body = request.get_json()
if request_body is not None:
task_ids = request_body['task_ids']
else:
task_ids = []

if request.method == "POST":
#update all the tasks to point to the goal
listoftasks = []
for taskid in task_ids:
mytask = Task.query.get(taskid)
mytask.goal_id = goal_id
listoftasks.append(taskid)
db.session.commit()
#return my_goal.goal_tasks_to_dict, 200
#Query all the tasks with the goalID
# create your response here and not in the db.models
return make_response({"id":int(goal_id), "task_ids":listoftasks}), 200

if request.method == "GET":
#set up a list
listoftasks = []
#Query all the tasks with the goalID
mytasks = Task.query.filter(Task.goal_id == goal_id)
for tasker in mytasks:
listoftasks.append(tasker.to_dict())
#return my_goal.goal_tasks_to_dict, 200

# create your response here and not in the db.models
return make_response({"id":int(goal_id), "title":my_goal.title, "tasks":listoftasks}), 200

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