Skip to content
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
10 changes: 7 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from flask import Flask
from flask import Flask , request , jsonify
from .db import db, migrate
from .models import task, goal
from .models.task import Task
from .models.goal import Goal
Comment on lines +1 to +4
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👀 There are several unused imports here that need to be removed.

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 @@ -17,6 +20,7 @@ def create_app(config=None):
db.init_app(app)
migrate.init_app(app, db)

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

return app
21 changes: 20 additions & 1 deletion app/models/goal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import Mapped, mapped_column, relationship
from ..db import db
from typing import Optional
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .task import Task

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")
Comment thread
divya42536 marked this conversation as resolved.

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

return goal_dict

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


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_as_dict = {}
task_as_dict["id"] = self.id
task_as_dict["title"] = self.title
task_as_dict["description"] = self.description
task_as_dict["is_complete"] = self.completed_at is not None
Comment thread
yangashley marked this conversation as resolved.
if self.goal_id:
task_as_dict["goal_id"] = self.goal_id
Comment thread
yangashley marked this conversation as resolved.

return task_as_dict



@classmethod
def from_dict(cls, task_data):
return cls(
title=task_data["title"],
description=task_data["description"],
completed_at=task_data.get("completed_at"),
goal_id=task_data.get("goal_id", None))
65 changes: 64 additions & 1 deletion app/routes/goal_routes.py
Original file line number Diff line number Diff line change
@@ -1 +1,64 @@
from flask import Blueprint
from ..routes.routes_utilities import validate_model, create_model, get_models_with_filters
from flask import abort, Blueprint, make_response, request , Response
from ..models.goal import Goal
from ..models.task import Task
from ..db import db
from datetime import datetime

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

@bp.post("")
def create_goal():
request_body = request.get_json()
return create_model(Goal, request_body)

@bp.post("/<id>/tasks")
def create_task_with_goal_id(id):
goal = validate_model(Goal, id)
request_body = request.get_json()
task_ids = request_body.get("task_ids", [])
tasks_to_add = []
for task_id in task_ids:
task = validate_model(Task, task_id)
tasks_to_add.append(task)
goal.tasks = tasks_to_add
db.session.commit()
response_body = {
"id": goal.id,
"task_ids": [task.id for task in goal.tasks]
}
return (response_body), 200


@bp.get("")
def get_all_goals():
return get_models_with_filters(Goal, request.args)

@bp.get("/<id>")
def get_goal(id):
goal = validate_model(Goal, id)
return goal.to_dict()

@bp.get("/<id>/tasks")
def get_all_goal_tasks(id):
goal = validate_model(Goal, id)
tasks = [task.to_dict() for task in goal.tasks]
response_body=goal.to_dict()
response_body["tasks"] = tasks
return response_body, 200


@bp.put("/<id>")
def replace_goal(id):
goal = validate_model(Goal, id)
request_body = request.get_json()
goal.title = request_body["title"]
db.session.commit()
return Response(status=204, mimetype="application/json")

@bp.delete("/<id>")
def delete_goal(id):
goal = validate_model(Goal, id)
db.session.delete(goal)
db.session.commit()
return Response(status=204, mimetype="application/json")
67 changes: 67 additions & 0 deletions app/routes/routes_utilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from flask import abort, make_response
from ..db import db
import requests
import os

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

query = db.select(cls).where(cls.id == id)
model = db.session.scalar(query)
if not model:
not_found = {"message": f"{cls.__name__} with id ({id}) not found."}
abort(make_response(not_found, 404))

return model

def create_model(cls, model_data):
try:
new_model = cls.from_dict(model_data)
except KeyError as e:
response = {"message": f"Invalid request: missing {e.args[0]}"}
abort(make_response(response, 400))

db.session.add(new_model)
db.session.commit()

return new_model.to_dict(), 201

def get_models_with_filters(cls, filters=None):
query = db.select(cls)
if filters:
for attribute, value in filters.items():
if attribute == "sort" and value.lower() == "asc":
query = query.order_by(cls.title.asc())
elif attribute == "sort" and value.lower() == "desc":
query = query.order_by(cls.title.desc())
elif hasattr(cls, attribute):
query = query.where(getattr(cls, attribute).ilike(f"%{value}%"))
models = db.session.scalars(query)
models_response = [model.to_dict() for model in models]
return models_response

def make_request_to_slack(task):
SLACK_URL = "https://slack.com/api/chat.postMessage"
SLACK_TOKEN = os.environ.get('SLACK_BOT_TOKEN')

if SLACK_TOKEN:
headers = {
"Authorization": f"Bearer {SLACK_TOKEN}",
"Content-Type": "application/json"
}
message = {
"channel": "#task-notifications",
"text": f"Someone just completed the task: {task.title}"
}

try:
response = requests.post(SLACK_URL, json=message, headers=headers)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Slack notification failed: {e}")
else:
print("SLACK_BOT_TOKEN not found in environment variables.")
60 changes: 59 additions & 1 deletion app/routes/task_routes.py
Original file line number Diff line number Diff line change
@@ -1 +1,59 @@
from flask import Blueprint
from flask import Blueprint, request, Response
from ..db import db
from ..models.task import Task
from .routes_utilities import validate_model, create_model, get_models_with_filters, make_request_to_slack
from datetime import datetime
import os
import requests

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

@bp.post("")
def create_task():
request_body = request.get_json()
return create_model(Task, request_body)

@bp.get("")
def get_all_tasks():
return get_models_with_filters(Task, request.args)

@bp.get("/<id>")
def get_single_task(id):
task = validate_model(Task, id)
return task.to_dict()

@bp.put("/<id>")
def replace_task(id):
task = validate_model(Task, id)
request_body = request.get_json()
task.title = request_body["title"]
task.description = request_body["description"]
if "completed_at" in request_body:
task.completed_at = request_body["completed_at"]
else:
task.completed_at = None
db.session.commit()
return Response(status=204, mimetype="application/json")

@bp.delete("/<id>")
def delete_task(id):
task = validate_model(Task, id)
db.session.delete(task)
db.session.commit()
return Response(status=204, mimetype="application/json")

@bp.patch("/<id>/mark_complete")
def mark_complete(id):
task = validate_model(Task, id)
task.completed_at = datetime.now()
db.session.commit()
make_request_to_slack(task)
return Response(status=204, mimetype="application/json")

@bp.patch("/<id>/mark_incomplete")
def mark_incomplete(id):
task = validate_model(Task, id)
task.completed_at = None
db.session.commit()
return Response(status=204, mimetype="application/json")

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