Exemple #1
0
def recipes(request, lookup, slug=None):
    """Fetch a single recipe."""
    recipe = Recipe.objects.get_slug(lookup)
    if recipe and recipe['slug'] != slug:
        raise Http404

    try:
        endpoint = reverse('api_recipes', args=[recipe['id']])
    except:
        raise Http404

    data = recipes_dict(recipe['id'], False)
    obj = data['data'][0]

    if obj:
        json_ld = {
            "@context": "http://schema.org",
            "@type": "Recipe",
            "name": obj['name'],
            "recipeYield": obj['servings'],
            "description": obj['description'],
            "datePublished": obj['pub_date'],
            "image": obj['img_small'],
            "recipeIngredient": [],
            "recipeInstructions": obj['instructions'],
        }

        sums = {
            'carbohydrates': 0,
            'energy_kcal': 0,
            'fat': 0,
            'fibers': 0,
            'protein': 0
        }

        for ingredient in obj['ingredients']:
            sums['carbohydrates'] += ingredient['carbohydrates']
            sums['energy_kcal'] += ingredient['energy_kcal']
            sums['fat'] += ingredient['fat']
            sums['fibers'] += ingredient['fibers']
            sums['protein'] += ingredient['protein']

            json_ld['recipeIngredient'].append(
                u"{} {} {}".format(
                    ingredient['amount'],
                    ingredient['unit_short'],
                    ingredient['text']
                )
            )

        json_ld['nutrition'] = {
            "@type": "NutritionInformation",
            "calories": "{} kcal".format(round(sums['protein'], 2)),
            "carbohydrateContent": "{} g".format(round(sums['energy_kcal'], 2)),
            "fatContent": "{} g".format(round(sums['fat'], 2)),
            "fiberContent": "{} g".format(round(sums['fibers'], 2)),
            "proteinContent": "{} g".format(round(sums['protein'], 2))
        }

    return render(
        request,
        'recipes/recipes.html',
        {
            'endpoint': endpoint,
            'page_title': recipe['name'],
            'page_description': json_ld['description'][:155] if json_ld['description'] else json_ld['recipeInstructions'][:155],
            'limit': settings.PAGE_LIMIT,
            'json_ld': json.dumps(json_ld)
        }
    )
Exemple #2
0
def api_recipes(request, recipe_id):
    """ Get recipe data for a singe recipe."""
    output = recipes_dict(recipe_id)
    if not output:
        raise Http404
    return JsonResponse(output)