def create_recipe(recipe_type=None, data=None, event=None, is_superseded=False, superseded=None): """Creates a recipe for unit testing :returns: The recipe model :rtype: :class:`recipe.models.Recipe` """ if not recipe_type: recipe_type = create_recipe_type() if not data: data = {} if not event: event = trigger_test_utils.create_trigger_event() if is_superseded and not superseded: superseded = timezone.now() recipe = Recipe() recipe.recipe_type = recipe_type recipe.recipe_type_rev = RecipeTypeRevision.objects.get_revision(recipe_type.id, recipe_type.revision_num) recipe.event = event recipe.data = data recipe.is_superseded = is_superseded recipe.superseded = superseded recipe.save() return recipe
def postrecipe(request): if request.method == 'POST': recipe_name = request.POST['recipe_name'] recipe_posted_by = request.user.id recipe_des = request.POST['recipe_des'] recipe_preptime = request.POST['recipe_preptime'] recipe_cooktime = request.POST['recipe_cooktime'] recipe_des = request.POST['recipe_des'] recipe_img1 = request.FILES.get('recipe_img1') recipe_img2 = request.FILES.get('recipe_img2') recipe_img3 = request.FILES.get('recipe_img3') recipe_img4 = request.FILES.get('recipe_img4') recipe_servings = request.POST['recipe_servings'] recipe_cat = request.POST['category'] data = Recipe(recipe_name=recipe_name, recipe_posted_by=User.objects.get(pk=recipe_posted_by), recipe_des=recipe_des, recipe_preptime=recipe_preptime, recipe_cooktime=recipe_cooktime, recipe_img1=recipe_img1, recipe_img2=recipe_img2, recipe_img3=recipe_img3, recipe_img4=recipe_img4, recipe_servings=recipe_servings, recipe_cat=Category.objects.get(pk=recipe_cat)) data.save() return render(request, 'recipe/post.html', {'success': 'Recipe Posted Successfully'}) else: catdata = Category.objects.all() return render(request, 'recipe/post.html', {'catdata': catdata})
def create_recipe(recipe_type=None, data=None, event=None): '''Creates a job type model for unit testing :param recipe_type: The associated recipe type :type recipe_type: :class:'recipe.models.RecipeType' :param data: The associated data for the recipe :type data: dict :param event: The associated event :type event: :class:'trigger.models.TriggerEvent' :returns: The recipe model :rtype: :class:`recipe.models.Recipe` ''' if not data: data = {} if not recipe_type: recipe_type = create_recipe_type() if not event: event = trigger_test_utils.create_trigger_event() recipe = Recipe() recipe.recipe_type = recipe_type recipe.recipe_type_rev = RecipeTypeRevision.objects.get_revision( recipe_type.id, recipe_type.revision_num) recipe.event = event recipe.data = data recipe.save() return recipe
def get(self, request, *args, **kwargs): for i in range(2, 120): try: url_list = 'https://eda.ru/recepty?page=' + str(i) resp = requests.get(url_list) soup = BeautifulSoup(resp.text) items = soup.findAll('h3', {'class': 'item-title'}) urls = [ 'https://eda.ru/' + [child for child in item.children][1]['href'] for item in items ] for url in urls: resp = requests.get(url) soup = BeautifulSoup(resp.text) title = soup.find('h1', { 'class': 'recipe__name' }).text.strip() steps = [[child for child in step.children][-1] for step in soup.findAll( 'span', {'class': 'instruction__description'}) ] recipe = Recipe(name=title) recipe.save() for step in steps: Instruction(step=step, recipe=recipe).save() except Exception as e: pass return HttpResponse('ok')
def create_recipe(recipe_type=None, data=None, event=None): '''Creates a job type model for unit testing :param recipe_type: The associated recipe type :type recipe_type: :class:'recipe.models.RecipeType' :param data: The associated data for the recipe :type data: dict :param event: The associated event :type event: :class:'trigger.models.TriggerEvent' :returns: The recipe model :rtype: :class:`recipe.models.Recipe` ''' if not data: data = {} if not recipe_type: recipe_type = create_recipe_type() if not event: event = trigger_test_utils.create_trigger_event() recipe = Recipe() recipe.recipe_type = recipe_type recipe.recipe_type_rev = RecipeTypeRevision.objects.get_revision(recipe_type.id, recipe_type.revision_num) recipe.event = event recipe.data = data recipe.save() return recipe
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
def recipeAdd(request): if request.method != 'POST': return sendError('No post request') if request.POST['name'] is None: return sendError('Name not defined') recipeIngredients = request.POST.getlist('ingredients', None) ingredientSet = checkIngredient(recipeIngredients) if ingredientSet is False: return sendError('Ingredients error') newRecipe = Recipe(name=request.POST['name'], description=request.POST.get('description', None), preparationTime=request.POST.get('preparationTime', None), backingTime=request.POST.get('backingTime', None), howmanypeoples=request.POST.get('howmanypeoples', None)) newRecipe.save() for ingredient in ingredientSet: Recipe_Ingredient.objects.create(ingredient=ingredient, recipe=newRecipe, quantity=1) return sendResponse(json.dumps({'status': 'success', 'id': newRecipe.id}))
def create_recipe(request): args = {'form': CreationFormRecipe} args.update(csrf(request)) if request.method == 'POST': form = CreationFormRecipe(request.POST, request.FILES) print(request.FILES) if form.is_valid(): data = form.data new_recipe = Recipe( recipe_name=data['recipe_name'], recipe_description=data['recipe_description'], recipe_ingredients=data['recipe_ingredients'], recipe_steps=data['recipe_steps'], recipe_photo=request.FILES['recipe_photo'], recipe_type_of_meal=data['recipe_type_of_meal'], recipe_author=User.objects.get(user_nickname='Антон')) new_recipe.save() return redirect('/recipe/') else: form = CreationFormRecipe() return render(request, 'recipes/create_recipe.html', args)
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 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(request): if request.method == "GET": return render(request, "add_recipe.html", context={"form": NewRecipeForm()}) if request.method == "POST": form = NewRecipeForm(request.POST) if form.is_valid(): recipe = Recipe(name=form.cleaned_data['name'], ingredients=form.cleaned_data['ingredients'], method=form.cleaned_data['method']) recipe.save() return render(request, "add_recipe.html", context={"form": form})
def test_create_recipe(self): recipe = Recipe() recipe.title = 'Recipechik' recipe.text = 'Some text' recipe.timestamp = timezone.now() recipe.save() all_recipes = Recipe.objects.all() the_recipe = Recipe.objects.get(id=recipe.id) self.assertEqual(the_recipe.text, recipe.text)
def create_recipe(recipe_type=None, input=None, event=None, is_superseded=False, superseded=None, superseded_recipe=None, batch=None, save=True): """Creates a recipe for unit testing :returns: The recipe model :rtype: :class:`recipe.models.Recipe` """ if not recipe_type: recipe_type = create_recipe_type() if not input: input = {} if not event: event = trigger_test_utils.create_trigger_event() if is_superseded and not superseded: superseded = timezone.now() recipe = Recipe() recipe.recipe_type = recipe_type recipe.recipe_type_rev = RecipeTypeRevision.objects.get_revision_old( recipe_type.id, recipe_type.revision_num) recipe.event = event recipe.input = input recipe.is_superseded = is_superseded recipe.superseded = superseded recipe.batch = batch if superseded_recipe: root_id = superseded_recipe.root_superseded_recipe_id if root_id is None: root_id = superseded_recipe.id recipe.root_superseded_recipe_id = root_id recipe.superseded_recipe = superseded_recipe if save: recipe.save() return recipe
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
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
def handle(self, *args, **kwargs): self.stdout.write("Ouverture du fichier de sauvegarde et restauration \ en cours. Merci de patienter...") directory_path = kwargs['path'][0] add_media = kwargs['add_media'][0] if 'database.json' not in os.listdir(directory_path): if 'recipe' not in os.listdir(directory_path): cmd1 = f"cd {directory_path}" cmd2 = "unzip backup_db.zip" os.system(f"{cmd1} && {cmd2}") if add_media == 'add-media': os.system( f"mv {directory_path}recipe \"{settings.MEDIA_ROOT}\"") jsonfile_path = directory_path + 'database.json' with open(jsonfile_path, 'r') as jsonfile: data = json.load(jsonfile) for mlp in data['meals_per_day']: try: MealsPerDay.objects.get(name=mlp) except: new_mlp = MealsPerDay(name=mlp) new_mlp.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_mlp.name)} \ ajouté à la base de données") for food_group in data['food_groups']: try: FoodGroup.objects.get(name=food_group) except: new_f_g = FoodGroup(name=food_group) new_f_g.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_f_g.name)} \ ajouté à la base de données") for food in data['foods']: try: Food.objects.get(name=food['name']) except: new_food = Food() for k, v in food.items(): if k == 'group_name': new_food.id_group = FoodGroup.objects.get(name=v) else: setattr(new_food, k, v) new_food.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_food.name)} \ ajouté à la base de données") for categ in data['recipe_categories']: try: CategorieRecipe.objects.get(name=categ['name']) except: new_categ = CategorieRecipe() new_categ.name = categ['name'] new_categ.image_active = categ['image_active'] new_categ.image_not_active = categ['image_not_active'] new_categ.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_categ.name)} \ ajouté à la base de données") for origin in data['origins_recipe']: try: OriginRecipe.objects.get(name=origin) except: new_origin = OriginRecipe(name=origin) new_origin.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_origin.name)} \ ajouté à la base de données") for level in data['levels']: try: Level.objects.get(name=level) except: new_level = Level(name=level) new_level.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_level.name)} \ ajouté à la base de données") for price_scale in data['price_scales']: try: PriceScale.objects.get(name=price_scale) except: new_p_s = PriceScale(name=price_scale) new_p_s.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_p_s.name)} \ ajouté à la base de données") for utensil in data['utensils']: try: Utensil.objects.get(name=utensil) except: new_u = Utensil(name=utensil) new_u.save() if kwargs['verbose']: self.stdout.write(f"{self.style.SUCCESS(new_u.name)} \ ajouté à la base de données") for season in data['seasons']: try: Season.objects.get(name=season) except: new_s = Season(name=season) new_s.save() if kwargs['verbose']: self.stdout.write(f"{self.style.SUCCESS(new_s.name)} \ ajouté à la base de données") for diet in data['diets']: try: DietaryPlan.objects.get(name=diet['name']) except: new_d = DietaryPlan(name=diet['name'], description=diet['desc']) new_d.save() if kwargs['verbose']: self.stdout.write(f"{self.style.SUCCESS(new_d.name)} \ ajouté à la base de données") for allergie in data['allergies']: try: Allergie.objects.get(name=allergie) except: new_a = Allergie(name=allergie) new_a.save() if kwargs['verbose']: self.stdout.write(f"{self.style.SUCCESS(new_a.name)} \ ajouté à la base de données") for recipe in data['recipes']: r_origin = OriginRecipe.objects.get(name=recipe['origin']) r_price_scale = PriceScale.objects.get( name=recipe['price_scale']) r_level = Level.objects.get(name=recipe['level']) categories = set() for categ in recipe['categories']: c = CategorieRecipe.objects.get(name=categ) categories.add(c) utensils = set() for utensil in recipe['utensils']: u = Utensil.objects.get(name=utensil) utensils.add(u) seasons = set() for season in recipe['season']: s = Season.objects.get(name=season) seasons.add(s) diets = set() for diet in recipe['dietary_plan']: d = DietaryPlan.objects.get(name=diet) diets.add(d) try: new_r = Recipe.objects.get(name=recipe['name']) state = 'modifiée' except: new_r = Recipe() state = 'ajoutée' new_r.name = recipe['name'] new_r.preparation_time = recipe['preparation_time'] new_r.cooking_time = recipe['cooking_time'] new_r.step = recipe['step'] new_r.tip = recipe['tip'] new_r.portion = recipe['portion'] new_r.point = recipe['point'] new_r.typical_recipe_city = recipe['typical_recipe_city'] new_r.source = recipe['source'] new_r.image = recipe['image'] new_r.origin = r_origin new_r.price_scale = r_price_scale new_r.level = r_level new_r.save() new_r.categories.set(categories) new_r.utensils.set(utensils) new_r.season.set(seasons) new_r.dietary_plan.set(diets) for food in recipe['food']: f = Food.objects.get(name=food['name']) fq = FoodAndQuantity() fq.food = f fq.recipe = new_r fq.recipe_quantity = food['recipe_quantity'] fq.recipe_unity = food['recipe_unity'] fq.food_purchase_quantity = food['purchase_quantity'] fq.food_purchase_unity = food['purchase_unity'] fq.save() if kwargs['verbose']: self.stdout.write( f"{self.style.SUCCESS(new_r.name)} {state} à la base de données" )