예제 #1
0
def update_item():
    """Saves changes to an existing item.

    :Returns: JSON with item ID or error message.
    """
    user_id = login_session['user_id']
    obj = request.get_json()
    item = obj.pop('item')
    item_id = item['id']
    rating = int(obj.pop('rating', 0))
    # Try to update the item using it's ID.
    try:
        app.q_MenuItem().filter_by(id=item_id).update(item)
        app.db_session.flush()
    except IntegrityError as e:
        app.db_session.rollback()
        return jsonify(error=e.orig.pgerror), 500
    # Create or update rating if rating > 0.
    if rating:
        try:
            # Try update.
            rating_rec = app.q_Rating().filter_by(item_id=item_id,
                                                  user_id=user_id).one()
            rating_rec.rating = rating
            app.db_session.flush()
        except NoResultFound:
            # Create new rating record.
            new_rating = MenuItemRating(rating=rating,
                                        item_id=item_id,
                                        user_id=user_id)
            app.db_session.add(new_rating)
            app.db_session.flush()
    # Commit changes and return item ID for reference.
    app.db_session.commit()
    return jsonify(id=item_id)
예제 #2
0
def api_menu(name=None, r_id=None):
    """Returns the menu for a restaurant in JSON format.

    Requires either the name or database ID number for a restaurant.
    You can get a list of restaurant names and ID numbers by using
    "/api/restaurants".

    :arg string restaurant: The name of a restaurant to lookup.
    :arg int restaurant_id: The database ID of a restaurant.
    :returns: JSON with a 'menu' key and a list of menu items.
    """
    if 'restaurant_id' in request.args:
        r_id = request.args.get('restaurant_id')
    if 'restaurant' in request.args:
        name = request.args.get('restaurant')
    if name:
        # Retrieve menu items by the given restaurant name.
        try:
            recs = app.q_MenuItem().join(Restaurant).filter_by(name=name)
        except NoResultFound:
            return jsonify(error='Restaurant not found.'), 400
        except MultipleResultsFound:
            resp = jsonify(error='Multiple restaurants found. Use ID instead.')
            return resp, 400
    else:
        # Retrieve menu items by the restaurant ID.
        recs = app.q_MenuItem().filter_by(restaurant_id=r_id)
    # Convert database objects to serializable dict objects.
    recs_json = [each.sdict for each in recs]
    return jsonify(menu=recs_json)
예제 #3
0
def api_menu(name=None, r_id=None):
    """Returns the menu for a restaurant in JSON format.

    Requires either the name or database ID number for a restaurant.
    You can get a list of restaurant names and ID numbers by using
    "/api/restaurants".

    :arg string restaurant: The name of a restaurant to lookup.
    :arg int restaurant_id: The database ID of a restaurant.
    :returns: JSON with a 'menu' key and a list of menu items.
    """
    if "restaurant_id" in request.args:
        r_id = request.args.get("restaurant_id")
    if "restaurant" in request.args:
        name = request.args.get("restaurant")
    if name:
        # Retrieve menu items by the given restaurant name.
        try:
            recs = app.q_MenuItem().join(Restaurant).filter_by(name=name)
        except NoResultFound:
            return jsonify(error="Restaurant not found."), 400
        except MultipleResultsFound:
            resp = jsonify(error="Multiple restaurants found. Use ID instead.")
            return resp, 400
    else:
        # Retrieve menu items by the restaurant ID.
        recs = app.q_MenuItem().filter_by(restaurant_id=r_id)
    # Convert database objects to serializable dict objects.
    recs_json = [each.sdict for each in recs]
    return jsonify(menu=recs_json)
예제 #4
0
def update_item():
    """Saves changes to an existing item.

    :Returns: JSON with item ID or error message.
    """
    user_id = login_session["user_id"]
    obj = request.get_json()
    item = obj.pop("item")
    item_id = item["id"]
    rating = int(obj.pop("rating", 0))
    # Try to update the item using it's ID.
    try:
        app.q_MenuItem().filter_by(id=item_id).update(item)
        app.db_session.flush()
    except IntegrityError as e:
        app.db_session.rollback()
        return jsonify(error=e.orig.pgerror), 500
    # Create or update rating if rating > 0.
    if rating:
        try:
            # Try update.
            rating_rec = app.q_Rating().filter_by(item_id=item_id, user_id=user_id).one()
            rating_rec.rating = rating
            app.db_session.flush()
        except NoResultFound:
            # Create new rating record.
            new_rating = MenuItemRating(rating=rating, item_id=item_id, user_id=user_id)
            app.db_session.add(new_rating)
            app.db_session.flush()
    # Commit changes and return item ID for reference.
    app.db_session.commit()
    return jsonify(id=item_id)
예제 #5
0
def get_items():
    """Returns a list of all menu items for a restaurant.

    Items are sorted by overall popularity: number of 'favorite' ratings down
    to number of 'dislike' ratings. Each item also includes the user's rating
    if a user is logged in.
    """
    r_id = request.args['id']
    recs = app.q_MenuItem().filter_by(restaurant_id=r_id)

    # Convert to serializable and add logged-in user's ratings for each item.
    user_id = login_session.get('user_id', None)
    serializable_recs = []
    for each_rec in recs:
        srec = each_rec.sdict
        for each_rating in each_rec.ratings:
            if each_rating.user_id == user_id:
                srec['rating'] = each_rating.rating
                break
        else:
            srec['rating'] = 0
        serializable_recs.append(srec)

    # Sort menu items by their popularity and return list.
    resp = sorted(serializable_recs,
                  key=lambda d:
                  (-d['favorite_count'], -d['good_count'], d['bad_count']))
    return jsonify(items=resp)
예제 #6
0
def get_items():
    """Returns a list of all menu items for a restaurant.

    Items are sorted by overall popularity: number of 'favorite' ratings down
    to number of 'dislike' ratings. Each item also includes the user's rating
    if a user is logged in.
    """
    r_id = request.args["id"]
    recs = app.q_MenuItem().filter_by(restaurant_id=r_id)

    # Convert to serializable and add logged-in user's ratings for each item.
    user_id = login_session.get("user_id", None)
    serializable_recs = []
    for each_rec in recs:
        srec = each_rec.sdict
        for each_rating in each_rec.ratings:
            if each_rating.user_id == user_id:
                srec["rating"] = each_rating.rating
                break
        else:
            srec["rating"] = 0
        serializable_recs.append(srec)

    # Sort menu items by their popularity and return list.
    resp = sorted(serializable_recs, key=lambda d: (-d["favorite_count"], -d["good_count"], d["bad_count"]))
    return jsonify(items=resp)
예제 #7
0
def delete_item():
    """Deletes an item from the database.

    :Returns: JSON object with status of 'ok' or HTML error message.
    """
    if 'id' not in request.get_json():
        return abort(400)
    if not isinstance(request.get_json()['id'], int):
        return abort(400)
    try:
        record = app.q_MenuItem().get(request.get_json()['id'])
        app.db_session.delete(record)
        app.db_session.commit()
        return jsonify(status='ok')
    except IntegrityError:
        app.db_session.rollback()
        return abort(500)
예제 #8
0
def delete_item():
    """Deletes an item from the database.

    :Returns: JSON object with status of 'ok' or HTML error message.
    """
    if "id" not in request.get_json():
        return abort(400)
    if not isinstance(request.get_json()["id"], int):
        return abort(400)
    try:
        record = app.q_MenuItem().get(request.get_json()["id"])
        app.db_session.delete(record)
        app.db_session.commit()
        return jsonify(status="ok")
    except IntegrityError:
        app.db_session.rollback()
        return abort(500)
예제 #9
0
def item_form(restaurant_id):
    """Returns a **private** page for adding or editing a menu item.

    Redirects to restaurant list if user is not logged in.
    """
    item_id = request.args.get('id', None)
    rating = request.args.get('rating', 0)
    restaurant = app.q_Restaurant().get(restaurant_id)
    context = {
        'title': 'Edit Item' if item_id else 'New Item',
        'restaurant': restaurant.sdict,
        'item': None,
        'rating': rating,
        'username': login_session.get('username', ''),
        'picture': login_session.get('picture', '')
    }
    if item_id is not None:
        context['item'] = app.q_MenuItem().get(item_id).sdict
    return render_template('form_item.html', **context)
예제 #10
0
def item_form(restaurant_id):
    """Returns a **private** page for adding or editing a menu item.

    Redirects to restaurant list if user is not logged in.
    """
    item_id = request.args.get('id', None)
    rating = request.args.get('rating', 0)
    restaurant = app.q_Restaurant().get(restaurant_id)
    context = {
        'title': 'Edit Item' if item_id else 'New Item',
        'restaurant': restaurant.sdict,
        'item': None,
        'rating': rating,
        'username': login_session.get('username', ''),
        'picture': login_session.get('picture', '')
    }
    if item_id is not None:
        context['item'] = app.q_MenuItem().get(item_id).sdict
    return render_template('form_item.html', **context)