Ejemplo n.º 1
0
    def create(self, validated_data):
        """
        Create a recipe instance.
        """
        username = validated_data['user']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise NotFound(detail='User not found.')

        name = validated_data['name']
        try:
            obj = Recipe.objects.get(user=user)
            raise ValidationError('recipe already exists for this user.')
        except Recipe.DoesNotExist:
            recipe = Recipe(name=name, user=user)
            recipe.save()

        steps = validated_data['steps']
        if steps:
            for step in steps:
                obj = Step(name=step, recipe=recipe)
                obj.save()

        ingredients = validated_data['ingredients']
        if ingredients:
            for ingredient in ingredients:
                obj = Ingredient(name=ingredient, recipe=recipe)
                obj.save()

        return recipe
Ejemplo n.º 2
0
 def handle(self,*args,**options):
     print("Loading data from file ingredienti.CSV")
     f = open('./ingredienti.CSV')
     for row in f:
         row = row.replace('\n','')
         dataline = row.split(';')
         new_ingredient = Ingredient()
         new_ingredient.name = dataline[0]
         new_ingredient.calories = dataline[1]
         new_ingredient.type = dataline[2]
         new_ingredient.save()
Ejemplo n.º 3
0
def add_recipe():
    with open("recipe_final.json", 'r') as f:
        data = json.load(f)

    user = User.objects.get(id=user_id)
    for idx, dt in enumerate(data):
        path_imgs, _ = get_list_images(os.path.join('images',dt['id']))
        # print(len(path_imgs))
        print(dt['name'])
        rec = Recipe()
        rec.name = dt['name']
        rec.user = user
        rec.servings = int(dt['servings'])
        rec.prep = dt['prep']
        # rec.cook = request.POST['cook']
        rec.total = dt['total']
        rec.total_min = parseTimes(dt['total'])
        rec.note = dt['notes']
        rec.rate = 0
        rec.description = dt['description']
        filename = os.path.join('images', dt['images'].split('%')[-1])
        rec.images = filename
        rec.save()

        for i in path_imgs:
            img = ImageRecipe()
            img.recipe = rec
            img.images = i.replace('images/','')
            img.save()

        categorys = dt['category']
        for i in categorys:
            cate = Category()
            cate.recipe = rec
            cate.name = i
            cate.save()

        ingredients = dt['ingredients']
        for i in ingredients:
            ing = Ingredient()
            ing.recipe = rec
            ing.content = i
            ing.save()

        ing_food = IngredientList(dt['ingredients'])
        for i in ing_food.all:
            math_food = MatchFood()
            math_food.recipe = rec
            math_food.food = Food.objects.get(id=i.matched_food.id)
            math_food.save()

        direction = dt['directions']
        for i in direction:
            dire = Direction()
            dire.recipe = rec
            dire.content = i
            dire.save()
        if idx == 100: break
Ejemplo n.º 4
0
    def post(self, request):
        rec = Recipe()
        rec.name = request.POST['name']
        if request.POST['note']:
            rec.note = request.POST['note']
        rec.description = request.POST['description']
        rec.servings = int(request.POST['servings'])
        prep, prep_min = parseTimes(request.POST['prep'],
                                    request.POST['prepTimeUnit'])
        cook, cook_min = parseTimes(request.POST['cook'],
                                    request.POST['cookTimeUnit'])
        rec.prep = prep
        rec.cook = cook
        rec.total_min = prep_min + cook_min
        image = request.FILES["image-file"]
        fs = FileSystemStorage()
        name = id_generator() + image.name
        filename = fs.save(name, image)
        rec.images = filename
        rec.rate = 0
        rec.user = request.user
        rec.save()

        img = ImageRecipe()
        img.recipe = rec
        img.images = filename
        img.save()

        categorys = request.POST['category']
        categorys = categorys.split(',')
        for i in categorys:
            if i.strip() == '':
                continue
            cate = Category()
            cate.recipe = rec
            cate.name = i.strip()
            cate.save()

        ingredients = request.POST['ingredient']
        ingredients = ingredients.split('\n')
        for i in ingredients:
            if i.strip() == '':
                continue
            ing = Ingredient()
            ing.recipe = rec
            ing.content = i.strip()
            ing.save()

        direction = request.POST['direction']
        direction = direction.split('\n')
        for i in direction:
            if i.strip() == '':
                continue
            dire = Direction()
            dire.recipe = rec
            dire.content = i.strip()
            dire.save()
        return HttpResponseRedirect('/share_recipe')
Ejemplo n.º 5
0
    def update(self, instance, validated_data):
        """
        Update a recipe instance.
        """
        username = validated_data['user']
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise NotFound(detail='User not found.')
        try:
            recipe = Recipe.objects.get(user=user)
            if recipe != instance:
                raise ValidationError('recipe already exists for this user.')
        except Recipe.DoesNotExist:
            instance.user = user

        instance.name = validated_data['name']
        instance.save()

        steps = validated_data['steps']
        step_qs = Step.objects.filter(recipe=instance).values_list('name',
                                                                   flat=True)
        for step in step_qs:
            if step in steps:
                steps.remove(step)
            else:
                Step.objects.filter(recipe=instance, name=step).delete()
        if steps:
            for step in steps:
                obj = Step(name=step, recipe=instance)
                obj.save()

        ingredients = validated_data['ingredients']
        ingredient_qs = Ingredient.objects.filter(recipe=instance).values_list(
            'name', flat=True)
        for ingredient in ingredient_qs:
            if ingredient in ingredients:
                ingredients.remove(ingredient)
            else:
                Ingredient.objects.filter(recipe=instance,
                                          name=ingredient).delete()
        if ingredients:
            for ingredient in ingredients:
                obj = Ingredient(name=ingredient, recipe=instance)
                obj.save()
        return instance
Ejemplo n.º 6
0
def recipe():
    ingredient = Ingredient()
    ingredient.name = "test_name_ingredient"
    ingredient.amount = "test_amount_ingredient"
    ingredient.save()

    user = User()
    user.name = 'test_name'
    user.email = "*****@*****.**"
    user.password = "******"
    user.save()

    recipe = Recipe()
    recipe.recipe_name = 'test_recipe'
    recipe.preparation_mode = 'test_preparation_mode'
    recipe.chef = user
    recipe.save()
    recipe.ingredient.add(ingredient)
    return recipe
Ejemplo n.º 7
0
def scrap_recipe_from_url(url):
	
	#fake test
	#url = 'https://www.marmiton.org/recettes/recette_bruschetta-aux-aubergines_47116.aspx'

	recipe = Recipe()
	recipe.url = url
	recipe.save() #force save to add children

	#get page
	response = requests.get(url)
	soup = BeautifulSoup(response.text, "html.parser")

	#detect the domain and get appropriate tags
	domain_name = url.split('/')[2]

	if (domain_name == 'www.marmiton.org'):
		allItems = soup.findAll("li", {"class": "recipe-preparation__list__item"})
		allIngredientQty = soup.findAll("span", {"class": "recipe-ingredient-qt"})
		allIngredientUnitAndNames = soup.findAll("span", {"class": "ingredient"})
		#allImages = soup.findAll("img", {"id": "recipe-media-viewer-main-picture"})
		imageDiv = soup.find("div", {"class": "recipe-media-viewer-media-container"})
		allImages = imageDiv.findAll("img")
		if (len(allImages) >0):
			img_url = allImages[0]['data-src']
	elif (domain_name == 'www.cuisineaz.com'):
		allItems = soup.findAll("p", {"class": "p10"})
		ingredientSection = soup.find("section", {"class": "large-4 medium-4 small-12 columns recipe_ingredients"})
		allIngredientQty = ingredientSection.findAll("span")
		allIngredientUnitAndNames = 'MANUAL'
		allImages = soup.findAll("img", {"id": "ContentPlaceHolder_recipeImg"})
		if (len(allImages) >0):
			img_url = allImages[0]['data-src']

	#get title
	allTitles = soup.findAll('h1')
	allTitles
	#recipe.name = 'fake name'
	recipe.name = allTitles[0].contents[0].strip()

	#TODO detect url domain, and store list of tags


	#get items list
	#allItems = soup.findAll("li", {"class": "recipe-preparation__list__item"})
	#current_item_tag = allItems[0]
	i=0
	for current_item_tag in allItems:
		currentListContent = ''
		for current_content in current_item_tag.contents:
			currentListContent =  current_content
		if i==0:
			recipe.description = '*' + currentListContent
		else:
			recipe.description = recipe.description + '\n' + currentListContent
		i=i+1

	#INGREDIENTS
	#allIngredientQty = soup.findAll("span", {"class": "recipe-ingredient-qt"})
	#allIngredientUnitAndNames = soup.findAll("span", {"class": "ingredient"})

	#loop on ingredient
	i=0
	for current_ingredient_qty in allIngredientQty:
		
		#print('ouuuuuuu')
		#print(current_ingredient_qty.contents)
		if(len(current_ingredient_qty.contents)<0):
			break
		#if(len(current_ingredient_qty.contents)==1):
			#<span>400g de semoule de blé complète</span>
			#currentQty=1
			#currentUnitAndName = current_ingredient_qty.contents[0]
		else:
			currentQty = current_ingredient_qty.contents[0]
			#currentUnitAndName = allIngredientUnitAndNames[i].contents[0]
			
			#for some sites we need to split 
			if (allIngredientUnitAndNames == 'MANUAL'):
				currentUnitAndName = current_ingredient_qty.contents[0]

				#KO for 60g without space
				number = re.search('^\d+', currentUnitAndName)
				if(number is None):
					#'sel, poivre'
					currentQty = 1
				else:
					currentQty = number.group(0)
					currentUnitAndName = currentUnitAndName[number.end():]



				#currentQty = current_ingredient_qty.contents[0].split(' ')[0]
				#currentUnitAndName = current_ingredient_qty.contents[0].split(' ', 1)[1]
			else:
				currentUnitAndName = allIngredientUnitAndNames[i].contents[0]
			#avoid non integer values in crappy websites

			#check if fraction?
			#if ('/' in currentQty):
			#	myFraction = Fraction(currentQty)
			#	currentQty = float(myFraction)

		#currentQty = math.ceil(float(currentQty))


		#TODO get ingredient by name or create it
		ingredient = Ingredient()
		ingredient.name=currentUnitAndName
		ingredient.save()

		#init ingredient qty object and add it to recipe
		ingredientQty = IngredientQuantity()
		ingredientQty.ingredient = ingredient
		ingredientQty.quantity = currentQty
		ingredientQty.recipe = recipe
		ingredientQty.save()

		i = i+1

	#image
	#allImages = soup.findAll("img", {"id": "recipe-media-viewer-main-picture"})
	if (len(allImages) >0):
		#img_url = allImages[0]['src']
		#recipe.comment = img_url

		# Steam the image from the url
		#request = requests.get(img_url, stream=True)
		
		# Get the filename from the url, used for saving later
		file_name = img_url.split('/')[-1]
		#content = urllib.request.urlretrieve(img_url)
		#recipe.image.save(file_name, File(open(content[0])), save=True)

		

		# save in the ImageField
		result = urllib.request.urlretrieve(img_url) # image_url is a URL to an image
		recipe.image.save(
    		file_name,
    		File(open(result[0], 'rb'))
    	)

		#SECOND ATTEMPT
		#request = requests.get(img_url, stream=True)
		#file = tempfile.NamedTemporaryFile()
		#request.raw.decode_content = True
		#shutil.copyfileobj(request.raw, file)
		#recipe.image = request.raw

	#recipe.name = 'fake name'
	recipe.save()
	return recipe
Ejemplo n.º 8
0
def ingredient():
    ingredient = Ingredient()
    ingredient.name = 'test_name_ingredient'
    ingredient.amount = "test_amount_ingredient"
    ingredient.save()
    return ingredient