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

C22 - Phoenix - Charday N. #73

Open
wants to merge 14 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
11 changes: 7 additions & 4 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from flask import Flask
from .db import db, migrate
from .models import task, goal
from .models.task import Task
from .models.goal import Goal
from .routes.task_routes import bp as tasks_bp
from .routes.goal_routes import bp as goals_bp
import os

def create_app(config=None):
Expand All @@ -10,13 +13,13 @@ def create_app(config=None):
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI')

if config:
# Merge `config` into the app's configuration
# to override the app's default settings for testing
app.config.update(config)

db.init_app(app)
migrate.init_app(app, db)

# Register Blueprints here
app.register_blueprint(tasks_bp)
app.register_blueprint(goals_bp)

return app
return app
13 changes: 11 additions & 2 deletions app/models/goal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
from sqlalchemy.orm import Mapped, mapped_column
from ..db import db
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db import db

class Goal(db.Model):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
title: Mapped[str]
tasks: Mapped[list["Task"]] = relationship(back_populates="goal")

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

@classmethod
def from_dict(cls, goal_data):
return cls(title=goal_data["title"])
27 changes: 26 additions & 1 deletion app/models/task.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
from sqlalchemy.orm import Mapped, mapped_column
from datetime import datetime
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import ForeignKey
from typing import Optional
from ..db import db

class Task(db.Model):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
title: Mapped[str]
description: Mapped[str]
completed_at: Mapped[Optional[datetime]]
goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id"))
goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks")

def to_dict(self):
task_to_dict = {
"id": self.id,
"title": self.title,
"description": self.description,
"is_complete": True if self.completed_at else False
}

if self.goal_id:
task_to_dict["goal_id"] = self.goal_id

return task_to_dict

@classmethod
def from_dict(cls, task_dict):
return Task(title=task_dict["title"] , description=task_dict["description"])
85 changes: 84 additions & 1 deletion app/routes/goal_routes.py
Original file line number Diff line number Diff line change
@@ -1 +1,84 @@
from flask import Blueprint
from flask import Blueprint, request, abort, make_response
from app.models.goal import Goal
from app.models.task import Task
from app.routes.route_utilities import create_model, validate_model
from app.db import db

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

@bp.post("")
def create_goal():
response = create_model(Goal, request.get_json())
return {"goal": response}, 201


@bp.post("/<goal_id>/tasks")
def add_tasks_to_goal(goal_id):
request_body = request.get_json()
goal = validate_model(Goal, goal_id)

try:
task_ids = request_body["task_ids"]
for task_id in task_ids:
task = validate_model(Task, task_id)
goal.tasks.append(task)

db.session.commit()

except KeyError as error:
response = {"details": f"Invalid request: missing {error.args[0]}"}
abort(make_response(response, 400))

return {"id": goal.id, "task_ids": task_ids}


@bp.get("")
def view_goals():
query = db.select(Goal).order_by(Goal.id)
goals = db.session.scalars(query)

return [goal.to_dict() for goal in goals]


@bp.get("/<goal_id>")
def view_goal(goal_id):
goal = validate_model(Goal, goal_id)
return {"goal": goal.to_dict()}


@bp.get("/<goal_id>/tasks")
def view_tasks_by_goal(goal_id):
goal = validate_model(Goal, goal_id)

goal_dict = goal.to_dict()
goal_dict["tasks"] = [task.to_dict() for task in goal.tasks]

return goal_dict


@bp.put("/<goal_id>")
def update_goal(goal_id):
goal = validate_model(Goal, goal_id)

request_body = request.get_json()
try:
goal.title = request_body["title"]
db.session.commit()

except KeyError as error:
response = {"details": f"Invalid request: missing {error.args[0]}"}
abort(make_response(response, 400))

return {"goal": goal.to_dict()}


@bp.delete("/<goal_id>")
def delete_goal(goal_id):
goal = validate_model(Goal, goal_id)

db.session.delete(goal)
db.session.commit()

response = f"Goal {goal_id} \"{goal.title}\" successfully deleted"

return {"details": response}
58 changes: 58 additions & 0 deletions app/routes/route_utilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from flask import abort, make_response
from app.db import db
import os, requests
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.environ.get("API_KEY")
CHANNEL_ID = os.environ.get("CHANNEL_ID")

def create_model(cls, model_data):
try:
model = cls.from_dict(model_data)

except KeyError as error:
response = {"details": f"Invalid data"}
abort(make_response(response, 400))

db.session.add(model)
db.session.commit()

return model.to_dict()


def validate_model(cls, model_id):
try:
model_id = int(model_id)

except ValueError:
response = {"message": f"Invalid request: {cls.__name__} id {model_id} invalid"}
abort(make_response(response, 400))

query = db.select(cls).where(cls.id == model_id)
model = db.session.scalar(query)
if model:
return model

response = {"message": f"Invalid request: {cls.__name__} {model_id} not found"}
abort(make_response(response, 404))


def send_slack_message(task_title):
url = "https://slack.com/api/chat.postMessage"
headers = {"Authorization": f"Bearer {API_KEY}"}
request_body = {
"channel": CHANNEL_ID,
"text": f"Someone just completed the task {task_title}"
}

try:
response = requests.post(url=url, headers=headers, json=request_body)
response.raise_for_status()
return response.json()

except:
abort(make_response({"message": "Unknkown request"}, 400))


79 changes: 78 additions & 1 deletion app/routes/task_routes.py
Original file line number Diff line number Diff line change
@@ -1 +1,78 @@
from flask import Blueprint
from flask import Blueprint, request
from sqlalchemy import desc
from datetime import datetime
from app.routes.route_utilities import create_model, validate_model, send_slack_message
from app.models.task import Task
from app.db import db


bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks")

@bp.post("")
def create_task():
response = create_model(Task, request.get_json())
return {"task": response}, 201


@bp.get("")
def get_tasks():
sort_param = request.args.get("sort")
query = db.select(Task)

if sort_param == "desc":
query = query.order_by(desc(Task.title))
else:
query = query.order_by(Task.title)

tasks = db.session.scalars(query)

return [task.to_dict() for task in tasks]


@bp.get("/<task_id>")
def get_task_by_id(task_id):
task = validate_model(Task, task_id)
return {"task": task.to_dict()}


@bp.put("/<task_id>")
def update_task(task_id):
task = validate_model(Task, task_id)
request_body = request.get_json()

task.title = request_body.get("title", task.title)
task.description = request_body.get("description", task.description)

db.session.commit()

return {"task": task.to_dict()}


@bp.patch("/<task_id>/mark_complete")
def update_task_as_complete(task_id):
task = validate_model(Task, task_id)
task.completed_at = datetime.now()
db.session.commit()

send_slack_message(task.title)

return {"task": task.to_dict()}


@bp.patch("/<task_id>/mark_incomplete")
def update_task_as_incomplete(task_id):
task = validate_model(Task, task_id)
task.completed_at = None
db.session.commit()

return {"task": task.to_dict()}


@bp.delete("/<task_id>")
def delete_task(task_id):
task = validate_model(Task, task_id)

db.session.delete(task)
db.session.commit()

return {"details": f"Task {task_id} \"{task.title}\" successfully deleted"}
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
50 changes: 50 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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,flask_migrate

[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

[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate

[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