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')
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
def test_creating_a_new_recipe(self): # Create a new recipe object with its recipe. recipe = Recipe() recipe.title = "What's up?" recipe.description = "This is a goldarn recipe." recipe.author = UserFactory.create() recipe.created = timezone.now() # Check if we can save it to the db recipe.save() # Now check if we can find it in the db again all_recipes_in_db = Recipe.objects.all() self.assertEqual(len(all_recipes_in_db), 1) only_recipe_in_db = all_recipes_in_db[0] self.assertEqual(only_recipe_in_db, recipe) # And check that it has saved its two attrbs, question and pub_date self.assertEqual(only_recipe_in_db.title, recipe.title) self.assertEqual(only_recipe_in_db.description, recipe.description)
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