예제 #1
0
파일: data.py 프로젝트: vabene1111/recipes
def import_url(request):
    if request.space.max_recipes != 0 and Recipe.objects.filter(
            space=request.space
    ).count(
    ) >= request.space.max_recipes:  # TODO move to central helper function
        messages.add_message(
            request, messages.WARNING,
            _('You have reached the maximum number of recipes for your space.')
        )
        return HttpResponseRedirect(reverse('index'))

    if request.space.max_users != 0 and UserPreference.objects.filter(
            space=request.space).count() > request.space.max_users:
        messages.add_message(
            request, messages.WARNING,
            _('You have more users than allowed in your space.'))
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        data = json.loads(request.body)
        data['cookTime'] = parse_cooktime(data.get('cookTime', ''))
        data['prepTime'] = parse_cooktime(data.get('prepTime', ''))

        recipe = Recipe.objects.create(
            name=data['name'],
            description=data['description'],
            waiting_time=data['cookTime'],
            working_time=data['prepTime'],
            servings=data['servings'],
            internal=True,
            created_by=request.user,
            space=request.space,
        )

        step = Step.objects.create(
            instruction=data['recipeInstructions'],
            space=request.space,
        )

        recipe.steps.add(step)

        for kw in data['keywords']:
            if data['all_keywords']:  # do not remove this check :) https://github.com/vabene1111/recipes/issues/645
                k, created = Keyword.objects.get_or_create(name=kw['text'],
                                                           space=request.space)
                recipe.keywords.add(k)
            else:
                try:
                    k = Keyword.objects.get(name=kw['text'],
                                            space=request.space)
                    recipe.keywords.add(k)
                except ObjectDoesNotExist:
                    pass

        ingredient_parser = IngredientParser(request, True)
        for ing in data['recipeIngredient']:
            ingredient = Ingredient(space=request.space, )

            if food_text := ing['ingredient']['text'].strip():
                ingredient.food = ingredient_parser.get_food(food_text)

            if ing['unit']:
                if unit_text := ing['unit']['text'].strip():
                    ingredient.unit = ingredient_parser.get_unit(unit_text)

            # TODO properly handle no_amount recipes
            if isinstance(ing['amount'], str):
                try:
                    ingredient.amount = float(ing['amount'].replace(',', '.'))
                except ValueError:
                    ingredient.no_amount = True
                    pass
            elif isinstance(ing['amount'], float) \
                    or isinstance(ing['amount'], int):
                ingredient.amount = ing['amount']
            ingredient.note = ing['note'].strip() if 'note' in ing else ''

            ingredient.save()
            step.ingredients.add(ingredient)
예제 #2
0
            if ing['unit'] and ing['unit']['text'] != '':
                ingredient.unit, u_created = Unit.objects.get_or_create(
                    name=ing['unit']['text']
                )

            # TODO properly handle no_amount recipes
            if isinstance(ing['amount'], str):
                try:
                    ingredient.amount = float(ing['amount'].replace(',', '.'))
                except ValueError:
                    ingredient.no_amount = True
                    pass
            elif isinstance(ing['amount'], float) \
                    or isinstance(ing['amount'], int):
                ingredient.amount = ing['amount']
            ingredient.note = ing['note'] if 'note' in ing else ''

            ingredient.save()
            step.ingredients.add(ingredient)
            print(ingredient)

        if 'image' in data and data['image'] != '':
            try:
                response = requests.get(data['image'])
                img = Image.open(BytesIO(response.content))

                # todo move image processing to dedicated function
                basewidth = 720
                wpercent = (basewidth / float(img.size[0]))
                hsize = int((float(img.size[1]) * float(wpercent)))
                img = img.resize((basewidth, hsize), Image.ANTIALIAS)
예제 #3
0
            if ing['unit'] and ing['unit']['text'] != '':
                ingredient.unit, u_created = Unit.objects.get_or_create(
                    name=ing['unit']['text'].strip(), space=request.space)

            # TODO properly handle no_amount recipes
            if isinstance(ing['amount'], str):
                try:
                    ingredient.amount = float(ing['amount'].replace(',', '.'))
                except ValueError:
                    ingredient.no_amount = True
                    pass
            elif isinstance(ing['amount'], float) \
                    or isinstance(ing['amount'], int):
                ingredient.amount = ing['amount']
            ingredient.note = ing['note'].strip() if 'note' in ing else ''

            ingredient.save()
            step.ingredients.add(ingredient)
            print(ingredient)

        if 'image' in data and data['image'] != '' and data[
                'image'] is not None:
            try:
                response = requests.get(data['image'])

                img, filetype = handle_image(request,
                                             BytesIO(response.content))
                recipe.image = File(
                    img, name=f'{uuid.uuid4()}_{recipe.pk}{filetype}')
                recipe.save()