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 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 test_partial_update(factory: APIRequestFactory, recipe: Recipe) -> None: """ Test API client can update one or more recipe's fields """ # Test data data = {"title": "Sausages With Potato Salad & Caramelised Onion"} # build url url = reverse("recipe-detail", args=(recipe.pk, )) # Create request object request = factory.patch(url, data, format="json") # Make request to api view view = RecipeViewSet.as_view(actions={"patch": "partial_update"}) response = view(request, pk=recipe.pk) old_title = recipe.title recipe.refresh_from_db() # Pull latest update from database after update # Test if request was successful assert response.status_code == 200 # Test updated field are returned assert response.data == data # Test recipe title was updated assert old_title != recipe.title
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 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, 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 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 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_recipe(self): self.new_recipe = Recipe(name="testrecipe", date_created=datetime.now(), created_by=self.user.id, date_modified=datetime.now()) db.session.add(self.new_recipe) db.session.commit()
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_rec_obj(r): name = r["Recipe Name"] img_url = r["Recipe Photo"] author = r["Author"] prepare_time = r["Prepare Time"] cook_time = r["Cook Time"] total_time = r["Total Time"] directions = r["Directions"] ingredients_list = r["Ingredients"] rec = Recipe(name = name, img_url = img_url, author = author, prepare_time = prepare_time, cook_time = cook_time, total_time = total_time, directions = directions, ingredients_list = ingredients_list) return rec
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 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 edit_recipe(request, recipe_id): if recipe_id is not None: recipe = get_object_or_404(Recipe, id=recipe_id) else: recipe = Recipe(author=request.user) editor = RecipeEditor(recipe, request) if recipe.author != request.user: return HttpResponseForbidden() if request.method == 'GET': return editor.render_get() elif request.method == 'POST': form = editor.validate_recipe_with_form() if form: form.save() editor.update_recipe_image() editor.create_recipe_tags() editor.create_recipe_ingredients() return redirect( reverse('single_page', kwargs=dict(recipe_id=recipe.id))) else: return editor.render_get(errors=editor.form_validation_errors)
def get(self, request, format=None): h = datetime.now().hour r = Recommend.get_recommend_by_hour(h) recommend = [] recipe_json = RecipeSerializer(r, many=True).data for item in recipe_json: item['recommendtype'] = 0 recommend.append(item) for item in RecommendArticle.objects.all(): article_json = ArticleSerializer(item.article).data article_json['recommendtype'] = 1 recommend.append(article_json) for item in RecommendSeries.objects.all(): series_json = SeriesSerializer(item.series).data series_json['recommendtype'] = 2 recommend.append(series_json) result = { 'recommend': recommend, 'theme': [ThemeSerializer(t.theme).data for t in RecommendTheme.objects.all()], 'update': RecipeSerializer(Recipe.get_latest_recipe(), many=True).data, } return self.success_response(result)
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 handle(self, *args, **options): with open('fixtures/recipe_fixture.json') as file: recipe_fixture = json.load(file) directions = defaultdict(list) ingredients = defaultdict(list) recipes = [] for key in recipe_fixture.keys(): recipe = recipe_fixture[key] ingredients[recipe['name']] = recipe['ingredients'] for d in recipe['instructions'].split('.'): directions[recipe['name']].append(d) recipes.append(Recipe( name=recipe['name'], servings=recipe['servings'], cook_time=recipe['cook_time'], prep_time=recipe['prep_time'], )) recipes_created = Recipe.objects.bulk_create(recipes, ignore_conflicts=True) recipes_qs = Recipe.objects.filter(name__in=[recipe.name for recipe in recipes_created]) ingredient_amts_to_create = [] directions_to_create = [] for r in recipes_qs: r_dirs = directions[r.name] for d in r_dirs: directions_to_create.append(Direction(recipe=r, text=d, name=d)) r_ings = ingredients[r.name] for i in r_ings: if i: i_split = i.split(' ') nums = list(filter(lambda x: hasNumbers(x), i_split)) amt = Fraction('0/1') if nums: try: amt = reduce(lambda x,y: Fraction(x) + Fraction(y), nums, Fraction('0/1')) except ValueError: pass i_unit = i_split[len(nums)] if amt else None b = int(bool(amt)) i_name = ' '.join(i_split[len(nums)+b:]) # print(amt, i_unit, i_name) if i_unit: unit, created = Unit.objects.get_or_create(name=i_unit, type=2, system=1) else: unit = None ing, created = Ingredient.objects.get_or_create(name=i_name) ingredient_amts_to_create.append(IngredientAmount(unit=unit, recipe=r, ingredient=ing, amount=Decimal(float(amt)))) # IngredientAmount.objects.bulk_create(ingredient_amts_to_create, ignore_conflicts=True) # for el in ingredient_amts_to_create: # i_a = IngredientAmount.objects.get(recipe=el.recipe, # ingredient=el.ingredient) # i_a.unit = el.unit # i_a.save() directions_created = Direction.objects.bulk_create(directions_to_create, ignore_conflicts=True) file.close()
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 create_recipe(recipe_type=None, input=None, event=None, is_superseded=False, superseded=None, superseded_recipe=None, config=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_v6() 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(recipe_type.name, recipe_type.revision_num) recipe.event = event recipe.input = input recipe.is_superseded = is_superseded recipe.superseded = superseded recipe.batch = batch recipe.configuration = config 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 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" )
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 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
from recipe.models import Recipe Recipe(name="Chorizo & mozzarella gnocchi bake", ingredients=""" 1 tbsp olive oil 1 onion , finely chopped 2 garlic cloves , crushed 120g chorizo , diced 2 x 400g cans chopped tomatoes 1 tsp caster sugar 600g fresh gnocchi 125g mozzarella ball, cut into chunks small bunch of basil , torn green salad , to serve""".replace("\n", "").strip(), method=""" Heat the oil in a medium pan over a medium heat. Fry the onion and garlic for 8-10 mins until soft. Add the chorizo and fry for 5 mins more. Tip in the tomatoes and sugar, and season. Bring to a simmer, then add the gnocchi and cook for 8 mins, stirring often, until soft. Heat the grill to high. Stir ¾ of the mozzarella and most of the basil through the gnocchi. Divide the mixture between six ovenproof ramekins, or put in one baking dish. Top with the remaining mozzarella, then grill for 3 mins, or until the cheese is melted and golden. Season, scatter over the remaining basil and serve with green salad.""".strip()).save() Recipe(name="Easy butter chicken", ingredients=""" 500g skinless boneless chicken thighs For the marinade 1 lemon, juiced 2 tsp ground cumin 2 tsp paprika 1-2 tsp hot chilli powder 200g natural yogurt For the curry 2 tbsp vegetable oil 1 large onion, chopped 3 garlic cloves, crushed 1 green chilli, deseeded and finely chopped (optional) thumb-sized piece ginger, grated