|
| 1 | +from flask import Blueprint, jsonify, request, abort |
| 2 | +from werkzeug.exceptions import BadRequest |
| 3 | +from Bizness import db |
| 4 | +from Bizness.models import Task |
| 5 | +from .api import BizResponse |
| 6 | +from config import PAGE_SIZE |
| 7 | +import iso8601 |
| 8 | + |
| 9 | + |
| 10 | +tasks_bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') |
| 11 | + |
| 12 | + |
| 13 | +@tasks_bp.route('/') |
| 14 | +def index(): |
| 15 | + """ |
| 16 | + request.args inherits from TypeConversionDict ! |
| 17 | + """ |
| 18 | + page_size = request.args.get('page_size', PAGE_SIZE, type=int) |
| 19 | + page = request.args.get('page', 1, type=int) |
| 20 | + last_date = request.args.get('last_date', None, type=lambda d: iso8601.parse_date(d)) |
| 21 | + |
| 22 | + if last_date is None: |
| 23 | + tasks_pagination = Task.paginate(page, page_size) |
| 24 | + else: |
| 25 | + tasks_pagination = Task.paginate_by_due_date(last_date, page_size) |
| 26 | + |
| 27 | + tasks = { |
| 28 | + 'tasks': [task.to_dict() for task in tasks_pagination.items] |
| 29 | + } |
| 30 | + |
| 31 | + response = BizResponse( |
| 32 | + success=True, |
| 33 | + data=tasks, |
| 34 | + total=tasks_pagination.total, |
| 35 | + page=tasks_pagination.page |
| 36 | + ) |
| 37 | + |
| 38 | + return jsonify(response.to_dict()) |
| 39 | + |
| 40 | + |
| 41 | +@tasks_bp.route('/', methods=['POST']) |
| 42 | +def create_task(): |
| 43 | + try: |
| 44 | + new_task = Task.from_request(request) |
| 45 | + db.session.add(new_task) |
| 46 | + db.session.commit() |
| 47 | + |
| 48 | + response = BizResponse( |
| 49 | + success=True, |
| 50 | + data=new_task.to_dict(), |
| 51 | + total=1 |
| 52 | + ) |
| 53 | + except BadRequest as e: |
| 54 | + response = BizResponse( |
| 55 | + success=False, |
| 56 | + data=e.description |
| 57 | + ) |
| 58 | + except Exception: |
| 59 | + response = BizResponse( |
| 60 | + success=False, |
| 61 | + data='An error occurred saving the task' |
| 62 | + ) |
| 63 | + |
| 64 | + return jsonify(response.to_dict()) |
| 65 | + |
| 66 | + |
| 67 | +@tasks_bp.route('/<int:task_id>', methods=['GET']) |
| 68 | +def get_task(task_id): |
| 69 | + task = Task.query.filter(Task.id == task_id).first() |
| 70 | + if task is None: |
| 71 | + abort(404) |
| 72 | + |
| 73 | + response = BizResponse( |
| 74 | + success=True, |
| 75 | + data=task.to_dict() |
| 76 | + ) |
| 77 | + |
| 78 | + return jsonify(response.to_dict()) |
0 commit comments