Coverage for cookbook/integration/cookbookapp.py: 24%

49 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2023-12-29 00:47 +0100

1import re 

2from io import BytesIO 

3 

4import requests 

5import validators 

6 

7from cookbook.helper.ingredient_parser import IngredientParser 

8from cookbook.helper.recipe_url_import import (get_from_scraper, get_images_from_soup, 

9 iso_duration_to_minutes) 

10from cookbook.helper.scrapers.scrapers import text_scraper 

11from cookbook.integration.integration import Integration 

12from cookbook.models import Ingredient, Recipe, Step 

13 

14 

15class CookBookApp(Integration): 

16 

17 def import_file_name_filter(self, zip_info_object): 

18 return zip_info_object.filename.endswith('.html') 

19 

20 def get_recipe_from_file(self, file): 

21 recipe_html = file.getvalue().decode("utf-8") 

22 

23 scrape = text_scraper(text=recipe_html) 

24 recipe_json = get_from_scraper(scrape, self.request) 

25 images = list(dict.fromkeys(get_images_from_soup(scrape.soup, None))) 

26 

27 recipe = Recipe.objects.create( 

28 name=recipe_json['name'].strip(), 

29 created_by=self.request.user, internal=True, 

30 space=self.request.space) 

31 

32 try: 

33 recipe.servings = re.findall('([0-9])+', recipe_json['recipeYield'])[0] 

34 except Exception: 

35 pass 

36 

37 try: 

38 recipe.working_time = iso_duration_to_minutes(recipe_json['prepTime']) 

39 recipe.waiting_time = iso_duration_to_minutes(recipe_json['cookTime']) 

40 except Exception: 

41 pass 

42 

43 # assuming import files only contain single step 

44 step = Step.objects.create(instruction=recipe_json['steps'][0]['instruction'], space=self.request.space, 

45 show_ingredients_table=self.request.user.userpreference.show_step_ingredients, ) 

46 

47 if 'nutrition' in recipe_json: 

48 step.instruction = step.instruction + '\n\n' + recipe_json['nutrition'] 

49 

50 step.save() 

51 recipe.steps.add(step) 

52 

53 ingredient_parser = IngredientParser(self.request, True) 

54 for ingredient in recipe_json['steps'][0]['ingredients']: 

55 f = ingredient_parser.get_food(ingredient['food']['name']) 

56 u = None 

57 if unit := ingredient.get('unit', None): 

58 u = ingredient_parser.get_unit(unit.get('name', None)) 

59 step.ingredients.add(Ingredient.objects.create( 

60 food=f, unit=u, amount=ingredient.get('amount', None), note=ingredient.get('note', None), original_text=ingredient.get('original_text', None), space=self.request.space, 

61 )) 

62 

63 if len(images) > 0: 

64 try: 

65 url = images[0] 

66 if validators.url(url, public=True): 

67 response = requests.get(url) 

68 self.import_recipe_image(recipe, BytesIO(response.content)) 

69 except Exception as e: 

70 print('failed to import image ', str(e)) 

71 

72 recipe.save() 

73 return recipe