Пример #1
0
def user_shopping_list(request):
    """
    Returns the user shopping list
    """
    user_id = crypto.decrypt(
        request.COOKIES['euid']) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)

    if user_id and session_id:
        user = User.get_by_id(user_id)
        start = request.GET.get('start', '0')
        label_error = False

        try:
            start = int(start)
        except ValueError:
            start = 0

        # Get shopping list products by user_id
        prod_entities = Shopping_List_Product.query(
            Shopping_List_Product.user_id == user_id).order(
                -Shopping_List_Product.added_on).fetch(limit=5, offset=start)

        # Get total number of shopping list
        total = Shopping_List_Product.query(
            Shopping_List_Product.user_id == user_id).count()

        products = []
        length = 0
        now = datetime.utcnow()

        for entity in prod_entities:
            # Get product detailed info
            prod_details = label_api.label_array(session_id, entity.barcode)

            if 'productsArray' in prod_details:
                products.append(prod_details['productsArray'][0])
                length += 1
                products[length - 1]['contains'] = []
                products[length - 1]['may_contain'] = []

                # Get nutrient percentage value
                for nutrient in products[length - 1]['nutrients']:
                    if nutrient[
                            'nutrient_name'] in constants.DAILY_VALUES and nutrient[
                                'nutrient_uom'] in constants.UNIT_MULTIPLIER:
                        try:
                            nutrient['percentage_value'] = '{:.0%}'.format(
                                float(nutrient['nutrient_value']) *
                                constants.UNIT_MULTIPLIER[
                                    nutrient['nutrient_uom']] /
                                constants.DAILY_VALUES[
                                    nutrient['nutrient_name']][1])
                        except ValueError:
                            nutrient['percentage_value'] = ''

                for allergen in products[length - 1]['allergens']:
                    if allergen['allergen_value'] == '2':
                        products[length - 1]['contains'].append(
                            allergen['allergen_name'])
                    elif allergen['allergen_value'] == '1':
                        products[length - 1]['may_contain'].append(
                            allergen['allergen_name'])

                for additive in products[length - 1]['additives']:
                    if additive['additive_value'] == '2':
                        products[length - 1]['contains'].append(
                            additive['additive_name'])
                    elif additive['additive_value'] == '1':
                        products[length - 1]['may_contain'].append(
                            additive['additive_name'])

                for ingredient in products[length - 1]['procingredients']:
                    if ingredient['value'] == 2:
                        products[length - 1]['contains'].append(
                            ingredient['name'])
                    elif ingredient['value'] == 1:
                        products[length - 1]['may_contain'].append(
                            ingredient['name'])

            else:
                label_error = True
                break

            # Check if product is on user shopping list
            if Pantry_Product.query(
                    Pantry_Product.user_id == user_id,
                    Pantry_Product.barcode == entity.barcode).get(
                        keys_only=True):
                products[length - 1]['in_pantry'] = 'true'

            # Get time between now when product was added
            products[length -
                     1]['t_delta'] = utils.get_time_delta_str(now -
                                                              entity.added_on)

        pages = get_pages(start, total)

        return render_to_response(
            'user_shopping_list.html', {
                'products': products,
                'products_len': len(products),
                'total': total,
                'start': start,
                'pages': pages,
                'label_error': label_error,
            }, RequestContext(request))

    return redirect('/signin')
Пример #2
0
def user_shopping_list(request):
    """
    Returns the user shopping list
    """
    user_id = crypto.decrypt(request.COOKIES['euid']) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)
    
    if user_id and session_id:
        user = User.get_by_id(user_id)
        start = request.GET.get('start', '0')
        label_error = False

        try:
            start = int(start)
        except ValueError:
            start = 0

        # Get shopping list products by user_id        
        prod_entities = Shopping_List_Product.query(
            Shopping_List_Product.user_id == user_id).order(
                -Shopping_List_Product.added_on).fetch(limit=5, offset=start)

        # Get total number of shopping list
        total = Shopping_List_Product.query(Shopping_List_Product.user_id == user_id).count()

        products = []
        length = 0
        now = datetime.utcnow()

        for entity in prod_entities:
            # Get product detailed info
            prod_details = label_api.label_array(session_id, entity.barcode)

            if 'productsArray' in prod_details:
                products.append(prod_details['productsArray'][0])
                length += 1
                products[length-1]['contains'] = []
                products[length-1]['may_contain'] = []

                # Get nutrient percentage value
                for nutrient in products[length-1]['nutrients']:
                    if nutrient['nutrient_name'] in constants.DAILY_VALUES and nutrient['nutrient_uom'] in constants.UNIT_MULTIPLIER:
                        try:
                            nutrient['percentage_value'] = '{:.0%}'.format(float(nutrient['nutrient_value']) * constants.UNIT_MULTIPLIER[nutrient['nutrient_uom']] / constants.DAILY_VALUES[nutrient['nutrient_name']][1])
                        except ValueError:
                            nutrient['percentage_value'] = ''

                for allergen in products[length-1]['allergens']:
                    if allergen['allergen_value'] == '2':
                        products[length-1]['contains'].append(allergen['allergen_name'])
                    elif allergen['allergen_value'] == '1':
                        products[length-1]['may_contain'].append(allergen['allergen_name'])

                for additive in products[length-1]['additives']:
                    if additive['additive_value'] == '2':
                        products[length-1]['contains'].append(additive['additive_name'])
                    elif additive['additive_value'] == '1':
                        products[length-1]['may_contain'].append(additive['additive_name'])

                for ingredient in products[length-1]['procingredients']:
                    if ingredient['value'] == 2:
                        products[length-1]['contains'].append(ingredient['name'])
                    elif ingredient['value'] == 1:
                        products[length-1]['may_contain'].append(ingredient['name'])

            else:
                label_error=True
                break

            # Check if product is on user shopping list
            if Pantry_Product.query(
                    Pantry_Product.user_id == user_id,
                    Pantry_Product.barcode == entity.barcode
            ).get(keys_only=True):
                products[length-1]['in_pantry'] = 'true'

            # Get time between now when product was added
            products[length-1]['t_delta'] = utils.get_time_delta_str(now - entity.added_on)

        pages = get_pages(start, total)

        return render_to_response(
            'user_shopping_list.html',
            {
                'products': products,
                'products_len': len(products),
                'total': total,
                'start': start,
                'pages': pages,
                'label_error': label_error,
            },
            RequestContext(request))

    return redirect('/signin')
Пример #3
0
def search(request):
    """
    Returns a list of search results.
    """
    search_term = request.GET.get('q').lower()
    start = request.GET.get('start', '0')
    mobile = request.GET.get('mobile')
    user = User.get_by_id(crypto.decrypt(
        request.COOKIES['euid'])) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)

    if not session_id:
        session = {}
        while 'session_id' not in session:
            session = label_api.create_session()
        session_id = session['session_id']
        label_api.set_profile(session_id)

    products = []  # list of product info dictionaries
    pages = []  # list of (page_start, page_label) tuples
    total_found = 0

    # If start is not an integer, set start to 0
    try:
        start = int(start)
    except ValueError:
        start = 0

    if user:
        profile_hash = crypto.get_hmac_sha256_hash(
            json.dumps(user.get_profile(), sort_keys=True))
    else:
        profile_hash = crypto.get_hmac_sha256_hash(
            json.dumps(
                {
                    "nutrients": [{
                        "name": "Calories",
                        "value": "true"
                    }, {
                        "name": "Total Fat",
                        "value": "true"
                    }, {
                        "name": "Cholesterol",
                        "value": "true"
                    }, {
                        "name": "Sodium",
                        "value": "true"
                    }, {
                        "name": "Total Carbohydrate",
                        "value": "true"
                    }, {
                        "name": "Dietary Fiber",
                        "value": "true"
                    }, {
                        "name": "Sugars",
                        "value": "true"
                    }, {
                        "name": "Protein",
                        "value": "true"
                    }],
                    "allergens": [{
                        "name": "Gluten",
                        "value": "true"
                    }],
                    "additives": [{
                        "name": "Preservatives",
                        "value": "true"
                    }],
                    "myingredients": [],
                    "mysort": [{
                        "sort_variable": "Calories",
                        "sort_order": 1,
                        "variable_type": 1
                    }],
                },
                sort_keys=True))

    cached = Search_Cache.query(Search_Cache.profile_hash == profile_hash,
                                Search_Cache.search_term == search_term,
                                Search_Cache.start == start).get()

    # Data in cache and less than 5 days old
    if cached and (datetime.utcnow() - cached.updated_on).days < 5:
        products = cached.products
        pages = cached.pages
        total_found = cached.nfound

    else:
        if cached: cached.key.delete()

        search_result = {}

        while 'numFound' not in search_result:
            search_result = label_api.search_products(session_id,
                                                      search_term,
                                                      start=start)

        total_found = search_result['numFound']

        if total_found > 0:
            products = search_result['productsArray']
            pages = get_pages(start, total_found)

        # Get product details
        for product in products:
            if product['product_size'].strip() == 'none':
                product['product_size'] = ''

            prod_details = label_api.label_array(session_id, product['upc'])

            if 'productsArray' in prod_details:
                product['details'] = prod_details['productsArray'][0]
                product['contains'] = []
                product['may_contain'] = []

                # Get nutrient percentage value
                for nutrient in product['details']['nutrients']:
                    if nutrient[
                            'nutrient_name'] in constants.DAILY_VALUES and nutrient[
                                'nutrient_uom'] in constants.UNIT_MULTIPLIER:
                        try:
                            nutrient['percentage_value'] = '{:.0%}'.format(
                                float(nutrient['nutrient_value']) *
                                constants.UNIT_MULTIPLIER[
                                    nutrient['nutrient_uom']] /
                                constants.DAILY_VALUES[
                                    nutrient['nutrient_name']][1])
                        except ValueError:
                            nutrient['percentage_value'] = ''

                for allergen in product['details']['allergens']:
                    if allergen['allergen_value'] == '2':
                        product['contains'].append(allergen['allergen_name'])
                    elif allergen['allergen_value'] == '1':
                        product['may_contain'].append(
                            allergen['allergen_name'])

                for additive in product['details']['additives']:
                    if additive['additive_value'] == '2':
                        product['contains'].append(additive['additive_name'])
                    elif additive['additive_value'] == '1':
                        product['may_contain'].append(
                            additive['additive_name'])

                for ingredient in product['details']['procingredients']:
                    if ingredient['value'] == 2:
                        product['contains'].append(ingredient['name'])
                    elif ingredient['value'] == 1:
                        product['may_contain'].append(ingredient['name'])

        # Add to cache
        Search_Cache(profile_hash=profile_hash,
                     search_term=search_term,
                     start=start,
                     products=products,
                     pages=pages,
                     nfound=total_found).put()

    for product in products:
        # Check if product is on user shopping list
        if user and Shopping_List_Product.query(
                Shopping_List_Product.user_id == user.key.id(),
                Shopping_List_Product.barcode
                == product['upc']).get(keys_only=True):
            product['on_shopping_list'] = 'true'

        # Check if product is on user shopping list
        if user and Pantry_Product.query(
                Pantry_Product.user_id == user.key.id(), Pantry_Product.barcode
                == product['upc']).get(keys_only=True):
            product['in_pantry'] = 'true'

    response = render_to_response(
        'search.html', {
            'search_term': search_term,
            'products': products,
            'products_len': len(products),
            'pages': pages,
            'start': start,
            'total_found': total_found,
        }, RequestContext(request))

    response.set_signed_cookie('session_id', session_id)

    return response
Пример #4
0
def search(request):
    """
    Returns a list of search results.
    """
    search_term = request.GET.get('q').lower()
    start = request.GET.get('start', '0')
    mobile = request.GET.get('mobile')
    user = User.get_by_id(crypto.decrypt(request.COOKIES['euid'])) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)

    if not session_id:
        session = {}
        while 'session_id' not in session:
            session = label_api.create_session()
        session_id = session['session_id']
        label_api.set_profile(session_id)

    products = [] # list of product info dictionaries
    pages = [] # list of (page_start, page_label) tuples
    total_found = 0

    # If start is not an integer, set start to 0
    try:
        start = int(start)
    except ValueError:
        start = 0

    if user:
        profile_hash = crypto.get_hmac_sha256_hash(json.dumps(user.get_profile(), sort_keys=True))
    else:
        profile_hash = crypto.get_hmac_sha256_hash(json.dumps({
            "nutrients": [
                {"name": "Calories", "value": "true"},
                {"name": "Total Fat", "value": "true"},
                {"name": "Cholesterol", "value": "true"},
                {"name": "Sodium", "value": "true"},
                {"name": "Total Carbohydrate", "value": "true"},
                {"name": "Dietary Fiber", "value": "true"},
                {"name": "Sugars", "value": "true"},
                {"name": "Protein", "value": "true"}
            ],
            "allergens": [
                {"name": "Gluten", "value": "true"}
            ],
            "additives": [
                {"name": "Preservatives", "value": "true"}
            ],
            "myingredients": [],
            "mysort": [
                {
                    "sort_variable": "Calories",
                    "sort_order": 1,
                    "variable_type": 1
                }
            ],
        }, sort_keys=True))

    cached = Search_Cache.query(
        Search_Cache.profile_hash == profile_hash,
        Search_Cache.search_term == search_term,
        Search_Cache.start == start).get()

    # Data in cache and less than 5 days old
    if cached and (datetime.utcnow() - cached.updated_on).days < 5:
        products = cached.products
        pages = cached.pages
        total_found = cached.nfound

    else:
        if cached: cached.key.delete()

        search_result = {}

        while 'numFound' not in search_result:
            search_result = label_api.search_products(session_id, search_term, start=start)

        total_found = search_result['numFound']

        if total_found > 0:
            products = search_result['productsArray']
            pages = get_pages(start, total_found)

        # Get product details
        for product in products:
            if product['product_size'].strip() == 'none':
                product['product_size'] = ''

            prod_details = label_api.label_array(session_id, product['upc'])

            if 'productsArray' in prod_details:
                product['details'] = prod_details['productsArray'][0]
                product['contains'] = []
                product['may_contain'] = []

                # Get nutrient percentage value
                for nutrient in product['details']['nutrients']:
                    if nutrient['nutrient_name'] in constants.DAILY_VALUES and nutrient['nutrient_uom'] in constants.UNIT_MULTIPLIER:
                        try:
                            nutrient['percentage_value'] = '{:.0%}'.format(float(nutrient['nutrient_value']) * constants.UNIT_MULTIPLIER[nutrient['nutrient_uom']] / constants.DAILY_VALUES[nutrient['nutrient_name']][1])
                        except ValueError:
                            nutrient['percentage_value'] = ''

                for allergen in product['details']['allergens']:
                    if allergen['allergen_value'] == '2':
                        product['contains'].append(allergen['allergen_name'])
                    elif allergen['allergen_value'] == '1':
                        product['may_contain'].append(allergen['allergen_name'])

                for additive in product['details']['additives']:
                    if additive['additive_value'] == '2':
                        product['contains'].append(additive['additive_name'])
                    elif additive['additive_value'] == '1':
                        product['may_contain'].append(additive['additive_name'])

                for ingredient in product['details']['procingredients']:
                    if ingredient['value'] == 2:
                        product['contains'].append(ingredient['name'])
                    elif ingredient['value'] == 1:
                        product['may_contain'].append(ingredient['name'])

        # Add to cache
        Search_Cache(profile_hash = profile_hash,
               search_term = search_term,
               start = start,
               products = products,
               pages = pages,
               nfound = total_found).put()

    for product in products:
        # Check if product is on user shopping list
        if user and Shopping_List_Product.query(
                Shopping_List_Product.user_id == user.key.id(),
                Shopping_List_Product.barcode == product['upc']
        ).get(keys_only=True):
            product['on_shopping_list'] = 'true'

        # Check if product is on user shopping list
        if user and Pantry_Product.query(
                Pantry_Product.user_id == user.key.id(),
                Pantry_Product.barcode == product['upc']
        ).get(keys_only=True):
            product['in_pantry'] = 'true'

    response = render_to_response(
        'search.html', 
        {
            'search_term': search_term,
            'products': products,
            'products_len': len(products),
            'pages': pages,
            'start': start,
            'total_found': total_found,
        },
        RequestContext(request))

    response.set_signed_cookie('session_id', session_id)

    return response