Exemplo n.º 1
0
def menu_post():
    """
    Take in a JSON object in the form of
    {
        "menus":
        [
            {
                "id": 1,
                "time_of_day": <one of ('breakfast', 'lunch', 'dinner')>,
                "date": <date string in the format YYYY-MM-DD>,
                "recipes": [a list of numeric (integer) ids representing the ids of recipes to associate to this menu]
            }, ...
        ]
    }

    Where for each entry in "menu" if there is an "id" attribute,
    it is assumed that we are updating an existing menu (because we wouldn't have the id otherwise),
    and the values given will update the record and its ingredients links in the database.

    Otherwise, if there is no "id" for an object, the system will assume the values
    given are for a new record in the database and will create a new record.

    :return: A JSON object of {"menu":[<list of JSON Objects corresponding to menus updated or created in the system]}
    """
    if not request.json or len(request.json) == 0:
        return jsonify({"error": "No JSON supplied"}), 400

    id_col = Menu.__keys__[0]
    menu = Menu()
    ret_val = []
    if not request.json.get('menus', None):
        return jsonify({"error": "Invalid schema"}), 400
    for m in request.json['menus']:
        menu_id = m.get(id_col, None)
        # check for data validity
        # Enforce a datetime format
        if m.get('date', None) and not check_date(m['date']):
            return jsonify({"error": "{} is not a valid date".format(m['date'])}), 400
        # Enforce enums
        if m.get('time_of_day', None):
            if m['time_of_day'] not in Menu.__columns__['time_of_day']:
                return jsonify({"error": "{} is not a valid time of day".format(m['time_of_day'])}), 400

        if menu_id:
            menu.find_by_id(menu_id)
            menu.update(**m)
            menu.flush()
        else:
            menu.create(**m)
        if m.get('recipes', None) is not None:
            try:
                menu.recipes = m['recipes']
            except TypeError:
                return jsonify(
                    {"error": "Invalid data. The recipes attribute must be a list of numeric recipe ids"}), 400

        ret_val.append(deepcopy(menu.data))

    return jsonify({"menus": ret_val})
Exemplo n.º 2
0
def get_menu_by_id(id):
    """
    Get a menu record by its id
    :param id: The id to find the record by
    :return: A JSON object representing a menu record along with its associated list of recipe objects
    """
    menu = Menu()
    menu_data = menu.find_by_id(id)

    if not menu_data:
        return jsonify({"error": "No menu with id {} found".format(id)}), 404

    menu_data['recipes'] = menu.recipes

    return jsonify(menu_data)