forked from AdaGold/task-list-api
-
Notifications
You must be signed in to change notification settings - Fork 36
Possum-Divya-task-list-api #33
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
divya42536
wants to merge
7
commits into
Ada-C24:main
Choose a base branch
from
divya42536:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2e02d75
Completed task-list-api
divya42536 e2bb83e
added
divya42536 b3b9e59
Added import stmt
divya42536 c7f9a1b
Update app/models/goal.py
divya42536 58269b0
Update app/models/task.py
divya42536 ad9a8a7
Updated test cases
divya42536 fb265bd
Updated test cases
divya42536 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
|
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"]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
yangashley marked this conversation as resolved.
|
||
| if self.goal_id: | ||
| task_as_dict["goal_id"] = self.goal_id | ||
|
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)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Single-database configuration for Flask. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.