Exemple #1
0
def delete_calorie():
    """Endpoint for deleting calorie records from the database.

    Args can be sent as key/value pairs in the query string ('GET'), or as
    key/value pairs in the content ('POST').
    Args:
        calorie_id: the id of the calorie to delete (REQUIRED)
    Return:
        A JSON representing deletion success or failure, with success
        representing the possibly new calorie total for that day so the client 
        may change pass/fail for any cached calories for that day.
    """
    if not utils.is_logged_in():
        response = make_response(json.\
            dumps('Must sign in to CRUD'), 403)
        response.headers['Content-Type'] = 'application/json'

    if request.values.get("calorie_id") and \
        len(request.values.get("calorie_id")) > 0:

        calorie_id = int(request.values.get("calorie_id"))
        calorie = DataManager.get_calorie(calorie_id=calorie_id)

        # check permissions
        if not utils.canCalorieCRUD(calorie.user_id, 
                login_session["user_id"], login_session["user_type_id"]):

            response = make_response(json.\
                dumps('Not authorized for cal actions for given user'), 403)
            response.headers['Content-Type'] = 'application/json'
            return response

        # update and return
        (daytotal, meets) = utils.pass_fail_cal(calorie)
        date = calorie.date
        num_calories = DataManager.get_calorie(calorie_id).num_calories
        result = DataManager.delete_calorie(calorie_id)
        if result == 1:
            return jsonify({"Message": "Successful deletion",
                            "Post": "deletion",
                            "Model": "calorie",
                            "id": calorie_id,
                            "num_calories": num_calories,
                            "daytotal": daytotal,
                            "date": date,
                            "old_date": False,
                            "old_date_meets": False,
                            "old_date_daytotal": False})
        else:
            response = make_response(json.\
                dumps('Calorie id did not match any in db'), 401)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        response = make_response(json.dumps('Invalid calorie id'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
Exemple #2
0
def add_calorie():
    """Endpoint for adding calorie records in the database.

    Args can be sent as key/value pairs in the query string ('GET'), or as
    key/value pairs in the content ('POST').
    All args are required.
    Args:
        user_id: the calorie's user id
        date: the calorie's date. must be given in 'YYYY-MM-DD' format
        time: the calorie's time. must be given as an hour, from 0 <= h <= 24
        text: the calorie's description
        amnt: the new number of calories
    Return:
        A JSON representing the database version(s) of the created calorie,
        with extra field representing the possibly new calorie total for that 
        day so the client may change pass/fail for any cached calories for that
        day.
    """
    if not utils.is_logged_in():
        response = make_response(json.\
            dumps('Must sign in to CRUD'), 403)
        response.headers['Content-Type'] = 'application/json'

    if request.values.get("user_id") and \
        len(request.values.get("user_id")) > 0:

        user_id = int(request.values.get("user_id"))
        if not utils.canCalorieCRUD(user_id, 
                login_session["user_id"], login_session["user_type_id"]):
            response = make_response(json.\
                dumps('Not authorized for cal actions for given user'), 403)
            response.headers['Content-Type'] = 'application/json'
            return response             
    else:
        response = make_response(json.dumps('Must provide valid user id'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    if request.values.get("date") and \
        len(request.values.get("date")) > 0:
        dates = bleach.clean(request.values.get("date")).split("-")
        date = datetime.date(int(dates[0]), int(dates[1]), int(dates[2]))
        if not utils.is_calorie_date(date):
            response = make_response(json.\
                dumps('date invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        response = make_response(json.dumps('Must provide valid date'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    if request.values.get("time") and \
        len(request.values.get("time")) > 0:
        time = datetime.time(int(request.values.get("time")))
        if not utils.is_calorie_time(time):
            response = make_response(json.\
                dumps('time invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        response = make_response(json.dumps('Must provide valid time'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    if request.values.get("text") and \
        len(request.values.get("text")) > 0:
        text = bleach.clean(request.values.get("text"))
        if not utils.is_calorie_text(text):
            response = make_response(json.dumps('text invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        response = make_response(json.dumps('Must provide valid text'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    if request.values.get("amnt") and \
        len(request.values.get("amnt")) > 0:
        amnt = request.values.get("amnt")
        if not utils.is_calorie_amount(amnt):
            response = make_response(json.dumps('amount invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        response = make_response(json.dumps('Must provide valid amount'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    cal_id = DataManager.add_calorie(user_id, date, time, text, amnt)
    calorie = DataManager.get_calorie(calorie_id=cal_id)

    if calorie:
        (daytotal, meets) = utils.pass_fail_cal(calorie)
        sCal = calorie.serialize
        sCal["daytotal"] = daytotal
        sCal["meets"] = meets
        sCal["old_date"] = False
        sCal["old_date_meets"] = False
        sCal["old_date_daytotal"] = False
        utils.pass_fail_cal(calorie)
        return jsonify(Data=[sCal])
    else:
        response = make_response(json.dumps('Internal server error'), 500)
        response.headers['Content-Type'] = 'application/json'
        return response
Exemple #3
0
def edit_calorie():
    """Endpoint for editing calorie records in the database.

    Args can be sent as key/value pairs in the query string ('GET'), or as
    key/value pairs in the content ('POST').
    Args are optional unless noted.
    Args:
        calorie_id: the id of the calorie to edit (REQUIRED)
        user_id: the new user id
        date: the new date. must be given in 'YYYY-MM-DD' format
        time: the new time. must be given as an hour, from 0 <= h <= 24
        text: the new description
        num_calories: the new number of calories
    Return:
        A JSON representing the database version of the updated calorie,         
        with extra field representing the possibly new calorie total for that 
        day so the client may change pass/fail for any cached calories for that
        day.
    """
    if not utils.is_logged_in():
        response = make_response(json.\
            dumps('Must sign in to CRUD'), 403)
        response.headers['Content-Type'] = 'application/json'

    if request.values.get("calorie_id") and \
        len(request.values.get("calorie_id")) > 0:
        calorie_id = int(request.values.get("calorie_id"))
    else:
        response = make_response(json.dumps('Must provide calorie id'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response  

    if request.values.get("user_id") and \
        len(request.values.get("user_id")) > 0:
        user_id = int(request.values.get("user_id"))
    else:
        user_id = None

    if request.values.get("date") and \
        len(request.values.get("date")) > 0:
        dates = bleach.clean(request.values.get("date")).split("-")
        date = datetime.date(int(dates[0]), int(dates[1]), int(dates[2]))
        if not utils.is_calorie_date(date):
            response = make_response(json.\
                dumps('date invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        date = None

    if request.values.get("time") and \
        len(request.values.get("time")) > 0:
        time = datetime.time(int(bleach.clean(request.values.get("time"))))
        if not utils.is_calorie_time(time):
            response = make_response(json.\
                dumps('time invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        time = None

    if request.values.get("text") and \
        len(request.values.get("text")) > 0:
        text = bleach.clean(request.values.get("text"))
        if not utils.is_calorie_text(text):
            response = make_response(json.\
                dumps('text invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        text = None

    if request.values.get("amnt") and \
        len(request.values.get("amnt")) > 0:
        amnt = bleach.clean(request.values.get("amnt"))
        if not utils.is_calorie_amount(amnt):
            response = make_response(json.\
                dumps('amount invalid'), 400)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        amnt = None 

    # check permissions
    calorie = DataManager.get_calorie(calorie_id=calorie_id)
    if not utils.canCalorieCRUD(calorie.user_id, 
            login_session["user_id"], login_session["user_type_id"]):
        response = make_response(json.\
            dumps('Not authorized for cal actions for given user'), 403)
        response.headers['Content-Type'] = 'application/json'
        return response

    if user_id and not utils.canCalorieCRUD(user_id, 
            login_session["user_id"], login_session["user_type_id"]):
        response = make_response(json.\
            dumps('Not authorized for cal actions for given user'), 403)
        response.headers['Content-Type'] = 'application/json'
        return response 

    # get additional info
    old_calorie = DataManager.get_calorie(calorie_id=calorie_id)
    (old_daytotal, old_meets) = utils.pass_fail_cal(old_calorie)

    # make the update and return
    DataManager.edit_calorie(calorie_id, user_id=user_id, date=date,
        time=time, text=text, num_calories=amnt)
    calorie = DataManager.get_calorie(calorie_id=calorie_id)
    date_changed = old_calorie.date != calorie.date

    if calorie:
        (daytotal, meets) = utils.pass_fail_cal(calorie)
        sCal = calorie.serialize
        sCal["daytotal"] = daytotal
        sCal["meets"] = meets
        sCal["old_date"] = old_calorie.date
        sCal["old_date_meets"] = old_meets
        sCal["old_date_daytotal"] = old_daytotal
        return jsonify(Data=[sCal])
    else:
        response = make_response(json.dumps('Internal server error'), 500)
        response.headers['Content-Type'] = 'application/json'
        return response
Exemple #4
0
def get_calorie():
    """Endpoint for serving calorie records from the database.

    Args can be sent as key/value pairs in the query string ('GET').
    All args are optional. Providing no args returns all calories.
    Args:
        calorie_id: the id of the calorie to get
        user_id: the user id of the calorie's owner
        date_from: the beginning date of the range of calories to get.
            must be given in 'YYYY-MM-DD' format
        date_to: the ending date of the range of calories to get.
            must be given in 'YYYY-MM-DD' format
        time_from: the beginning time of the range of calories to get.
            must be given as an hour, from 0 <= h <= 24
        time_to: the ending time of the range of calories to get
            must be given as an hour, from 0 <= h <= 24
    Return:
        A JSON representing the database version(s) of the calorie(s) specified
        by the given arguments
    """
    if not utils.is_logged_in():
        response = make_response(json.\
            dumps('Must sign in to CRUD'), 403)
        response.headers['Content-Type'] = 'application/json'

    if request.values.get("calorie_id") and \
        len(request.values.get("calorie_id")) > 0:
        calorie_id = int(bleach.clean(request.values.get("calorie_id")))
        # check permissions for reading this calorie
        calorie = DataManager.get_calorie(calorie_id=calorie_id)
        if not utils.canCalorieCRUD(calorie.user_id, 
                login_session["user_id"], login_session["user_type_id"]):
            response = make_response(json.\
                dumps('Not authorized for cal actions for given user'), 403)
            response.headers['Content-Type'] = 'application/json'
            return response 
    else:
        calorie_id = None

    if request.values.get("user_id") and \
        len(request.values.get("user_id")) > 0:
        user_id = int(bleach.clean(request.values.get("user_id")))
        # check perissions for reading this user's calories
        if not utils.canCalorieCRUD(user_id, 
                login_session["user_id"], login_session["user_type_id"]):
            response = make_response(json.\
            dumps('Not authorized for cal actions for given user'), 403)
            response.headers['Content-Type'] = 'application/json'
            return response
    else:
        user_id = None    

    if request.values.get("date_from") and \
        len(request.values.get("date_from")) > 0:
        dates = request.values.get(bleach.clean("date_from")).split("-")
        date_from = datetime.date(int(dates[0]), int(dates[1]), int(dates[2]))
    else:
        date_from = datetime.date.min

    if request.values.get("date_to") and \
        len(request.values.get("date_to")) > 0:
        dates = request.values.get(bleach.clean("date_to")).split("-")
        date_to = datetime.date(int(dates[0]), int(dates[1]), int(dates[2]))
    else:
        date_to = datetime.date.max

    if request.values.get("time_from") and \
        len(request.values.get("time_from")) > 0:
        time_from = datetime.time(int(request.values.get("time_from")))
    else:
        time_from = datetime.time.min

    if request.values.get("time_to") and \
        len(request.values.get("time_to")) > 0:
        time_to = datetime.time(int(request.values.get("time_to")))
    else:
        time_to = datetime.time.max

    calorie = DataManager.get_calorie(calorie_id=calorie_id, 
        user_id=user_id, date_from=date_from, date_to=date_to, 
        time_from=time_from, time_to=time_to)

    # if results, set daytotal and whether the calorie falls on passing day
    if not type(calorie) is list:
        # single result
        (daytotal, meets) = utils.pass_fail_cal(calorie)
        sCal = calorie.serialize
        sCal["daytotal"] = daytotal
        sCal["meets"] = meets
        sCal["old_date"] = False
        sCal["old_date_meets"] = False
        sCal["old_date_daytotal"] = False
        utils.pass_fail_cal(calorie)
        return jsonify(Data=[sCal])
    elif len(calorie) > 0:
        # multiple results
        sCals = []
        for cal in calorie:
            (daytotal, meets) = utils.pass_fail_cal(cal)
            sCal = cal.serialize
            sCal["daytotal"] = daytotal
            sCal["meets"] = meets
            sCal["old_date"] = False
            sCal["old_date_meets"] = False
            sCal["old_date_daytotal"] = False
            sCals.append(sCal)
        return jsonify(Data=sCals)
    else:
        # no results, return empty list
        return jsonify(Data=[])