def feed_data_to_database(self): recipes = self.get_matching_recipes() for recipe in recipes: recipe_obj = Recipe(title=recipe[10], date_published=recipe[2], rating=recipe[8]) recipe_obj.save() for category_name in recipe[1]: category = None try: category = Category.objects.get(name=category_name) except: category = Category(name=category_name) category.save() rc = RecipeCategory(recipe=recipe_obj, category=category) rc.save() for id, direction_item in enumerate(recipe[4]): direction = Direction(content=direction_item, recipe=recipe_obj, order=(id + 1)) direction.save() for detailed_ingredient in recipe[6]: ingr = Ingredient.objects.get(name=detailed_ingredient[0]) dg = DetailedIngredient(recipe=recipe_obj, name=detailed_ingredient[1], ingredient=ingr) dg.save()
class RecipeRelatedTest(StaticLiveServerTestCase): """ Base class for functional tests dealing with recipes. Simple setup defined to avoid repetition. """ @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def setUp(self): self.username = '******' self.password = '******' self.user = User.objects.create_superuser(self.username, '*****@*****.**', self.password) self.category = FoodCategory(name='Example Cat') self.category.save() img = SimpleUploadedFile( 'example.jpg', content=open('/home/wroku/Dev/muconfi/mc/media_cdn/tree.JPG', 'rb').read(), content_type='image/jpeg') defaults = { 'name': 'Ing', 'category': self.category, 'image': img, 'price': 10, 'calval': 100, 'total_carbs': 10, 'total_fat': 10, 'total_proteins': 10, 'accepted': True } self.NUMBER_OF_INGREDIENTS = 5 for i in range(1, self.NUMBER_OF_INGREDIENTS + 1): defaults['name'] = defaults['name'][:3] + str(i) ingredient = Ingredient(**defaults) ingredient.save() self.recipe = Recipe(recipe_name='Model recipe', accepted=True, preparation_time=50, recipe_image='tree.JPG', directions='Ing') self.recipe.save() for i in range(1, self.NUMBER_OF_INGREDIENTS + 1): Quantity(recipe=self.recipe, ingredient=Ingredient.objects.get(name=f'Ing{i}'), quantity=100 + i).save()
def post(self, request): form = RecipeCreateForm(request.POST, request.FILES) if form.is_valid(): r = Recipe() r.name = form.cleaned_data['name'] r.ingredient_list = form.cleaned_data['ingredient_list'] r.instructions = form.cleaned_data['instructions'] r.photo = request.FILES['photo'] r.is_user_recipe = True r.creator = request.user.profile r.save() messages.success(request, "Recipe created.") return redirect('recipe_detail', pk=r.id) else: messages.error(request, "Invalid input, correct errors below.") return render(request, 'main/user_recipe_create.html', {'form': form})
def setUp(self): self.username = '******' self.password = '******' self.user = User.objects.create_superuser(self.username, '*****@*****.**', self.password) self.category = FoodCategory(name='Example Cat') self.category.save() img = SimpleUploadedFile( 'example.jpg', content=open('/home/wroku/Dev/muconfi/mc/media_cdn/tree.JPG', 'rb').read(), content_type='image/jpeg') defaults = { 'name': 'Ing', 'category': self.category, 'image': img, 'price': 10, 'calval': 100, 'total_carbs': 10, 'total_fat': 10, 'total_proteins': 10, 'accepted': True } self.NUMBER_OF_INGREDIENTS = 5 for i in range(1, self.NUMBER_OF_INGREDIENTS + 1): defaults['name'] = defaults['name'][:3] + str(i) ingredient = Ingredient(**defaults) ingredient.save() self.recipe = Recipe(recipe_name='Model recipe', accepted=True, preparation_time=50, recipe_image='tree.JPG', directions='Ing') self.recipe.save() for i in range(1, self.NUMBER_OF_INGREDIENTS + 1): Quantity(recipe=self.recipe, ingredient=Ingredient.objects.get(name=f'Ing{i}'), quantity=100 + i).save()
class BaseRecipeRelatedTest(TestCase): """ Separated setUp for recipe related test to avoid violating DRY. """ def setUp(self): self.category = FoodCategory(name='Example Cat') self.category.save() # This user has autogenerated id=1, Recipe model default User.objects.create_user(username="******", is_superuser=True, password="******") self.recipe = Recipe(recipe_name='Example Recipe') self.recipe2 = Recipe(recipe_name='Second Recipe') self.recipe.save() self.recipe2.save() defaults = { 'name': 'Ing', 'category': self.category, 'price': 10, 'calval': 100, 'total_carbs': 10, 'total_fat': 10, 'total_proteins': 10 } for i in range(1, 6): defaults['name'] = defaults['name'][:3] + str(i) defaults['price'] += 1 defaults['calval'] += 10 defaults['total_carbs'] += 4 defaults['total_fat'] += 4 defaults['total_proteins'] += 4 ingredient = Ingredient(**defaults) ingredient.save() Quantity(recipe=self.recipe, ingredient=ingredient, quantity=100).save() # Second recipe is created without ing1 for the sake of search_by_ing test if i != 1: Quantity(recipe=self.recipe2, ingredient=ingredient, quantity=50).save()
def read_file(self): with open(filename, 'r') as csvfile: reader = csv.reader(csvfile, delimiter='|', quotechar='"') count = 0 for row in reader: count += 1 if count == 1: # First row is column names continue r = Recipe()
def test_invalid_duplicate_name(self): """ Create recipe which will be occupying chosen name to trigger clean_recipe_name """ User.objects.create_superuser('Necessary Evil', '*****@*****.**', 'SomeP5WD-40') Recipe(recipe_name=self.default_data['recipe_name'], accepted=True, preparation_time=50, recipe_image='tree.JPG', directions='blablablab').save() form = RecipeForm(data=self.default_data, files=self.files, collect_ing=[]) self.assertFalse(form.is_valid()) self.assertIn( 'This title has already been used. Please type another one.', dict(form.errors)['recipe_name'])
def read_csv(self): print('Creating recipes in database...', end='', flush=True) start_time = time.time() with open(self.recipe_file, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') headers = next(reader) count = 0 # Columns: id,bitter,meaty,salty,sour,sweet,piquant,ingredients,recipeName,smallImageUrls,totalTimeInSeconds,rating,sourceDisplayName for row in reader: # If image url is http:, change to https: image_url = row[9].split(' ')[0] if image_url[:5] == 'http:': image_url = "{}s{}".format(image_url[:4], image_url[4:]) r = Recipe() r.yummly_url = row[0] r.bitter = row[1] r.meaty = row[2] r.salty = row[3] r.sour = row[4] r.sweet = row[5] r.piquant = row[6] r.ingredient_list = row[7].lower() r.name = row[8] r.yummly_image_url = image_url # r.yummly_time_in_seconds = row[10] if (row[10] != '') else 0 r.yummly_rating = row[11] r.yummly_source = row[12] r.is_yummly_recipe = True r.save() # For each ingredient in list, add to many to many field # self.add_ingredients(r) # Now managed in Recipe post_save method count += 1 if count % 100 == 0: print('.', end='', flush=True) print("") self.stdout.write(self.style.SUCCESS('Finished importing {} into db: {} recipes, {} ingredients (took {} minutes).'\ .format(self.recipe_file, Recipe.objects.count(), Ingredient.objects.count(), int((time.time()-start_time)/60)) ))
def handle(self, *args, **options): self.delete_existing() with open(filename, 'r') as csvfile: reader = csv.reader(csvfile, delimiter='|', quotechar='"') count = 0 for row in reader: if row[4] == '': # If empty value for calories, default row[4] = 0 r = Recipe() r.url = row[0] r.name = row[1] r.source = row[2] r.rating = row[3] r.time_in_seconds = row[4] r.tags = row[5] r.ingredient_list = row[6] r.isYummlyRecipe = True r.save() # for each ingredient in list, add to many to many field self.add_ingredients(r) count += 1 if count >= 100: break self.stdout.write(self.style.SUCCESS('Finished importing {} into db ({} recipes, {} ingredients).'\ .format(filename, Recipe.objects.count(), Ingredient.objects.count()) ))