コード例 #1
0
def handle_goals():
    if request.method == "GET":
        direction = request.args.get("sort")
        if direction == "asc":
            goals = Goal.query.order_by(asc("title"))
        elif direction == "desc":
            goals = Goal.query.order_by(desc("title"))
        else:
            goals = Goal.query.all()

        goals_response = [goal.to_dict() for goal in goals]

        return jsonify(goals_response)

    elif request.method == "POST":
        request_body = request.get_json()
        try:
            new_goal = Goal(title=request_body["title"])
        except KeyError:
            return make_response({"details": "Invalid data"}, 400)

        db.session.add(new_goal)
        db.session.commit()

        return make_response({"goal": new_goal.to_dict()}, 201)
コード例 #2
0
def handle_goals():
    if request.method == "GET":
        query_param_value = request.args.get("sort")
        if query_param_value == "asc":
            goals = Task.query.order_by(Goal.title.asc())
        elif query_param_value == "desc":
            goals = Task.query.order_by(Goal.title.desc())
        else:
            goals = Goal.query.all()

        goals_response = []
        for goal in goals:
            goals_response.append(goal.to_dict())
        return jsonify(goals_response), 200

    elif request.method == "POST":
        request_body = request.get_json()

        # Invalid goal if missing title
        if "title" not in request_body:
            return jsonify({"details": "Invalid data"}), 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)
コード例 #3
0
ファイル: routes.py プロジェクト: lzhang39/task-list-api
def create_goal():
    request_body = request.get_json()
    if "title" in request_body:
        new_goal = Goal(title=request_body["title"])
        db.session.add(new_goal)
        db.session.commit()
        return jsonify({"goal": new_goal.to_dict()}), 201
    return make_response({"details": "Invalid data"}, 400)