Exemple #1
0
def setup_function(function):
  cuisine = Cuisine(name="vietnamese")
  cuisine.save()
  restaurant = Restaurant(name="tu lan", location="123 address", cuisine=cuisine)
  restaurant.save()
  food = Food(**{
      "name": "Pho bo",
      "cuisine": cuisine,
      "restaurant": restaurant,
      "price": 8.75,
      "avgRating": 4.5,
      "numRating": 10
    })
  food.save()
  userChew = User(user="******")
  userChew.save()
  userHungry = User(user="******")
  userHungry.save()
  review = Review(**{
    "food": food,
    "text": "Wow this was delicious!",
    "user": userChew,
    "foodRating": 4,
    "reviewRating": 0,
    })
  review.save()
  reviewTwo = Review(**{
    "food": food,
    "text": "Wow this was delicious!",
    "user": userHungry,
    "foodRating": 4,
    "reviewRating": 0,
    })
  reviewTwo.save()
  function.parametrize(review);
Exemple #2
0
 def populate(self):
     """ Class method, which allows the user to populate the Database """
     data = api_research_off()
     for product in data['products']:
         product_name = self.get_product_name(product)
         nutriscore = self.get_nutriscore(product)
         if nutriscore is None:
             continue
         nutritional_list = self.get_nutritional_mark_for_100g(product)
         if nutritional_list is None:
             continue
         url_page = self.get_url_page(product)
         url_image = self.get_url_image(product)
         if (not url_image):
             continue
         id_product = self.get_id_product_and_check_if_exists(product)
         if (not id_product) or id_product is None:
             continue
         last_modified_date = self.get_last_modified(product)
         food = Food(name=product_name,
                     nutriscore=nutriscore,
                     url=url_page,
                     url_picture=url_image,
                     fat_100g=nutritional_list[0],
                     saturated_fat_100g=nutritional_list[2],
                     sugars_100g=nutritional_list[4],
                     salt_100g=nutritional_list[6],
                     fat_level=nutritional_list[1],
                     salt_level=nutritional_list[7],
                     saturated_fat_level=nutritional_list[3],
                     sugars_level=nutritional_list[5],
                     last_modified=last_modified_date,
                     openff_id=id_product)
         food.save()
         self.get_and_insert_categories_in_db(product, food)
Exemple #3
0
def update():
    """ Class method, which update the Database """
    data = api_research_off()
    for product in data['products']:
        product_name = db.get_product_name(product)
        nutriscore = db.get_nutriscore(product)
        if nutriscore is None:
            continue
        nutritional_list = db.get_nutritional_mark_for_100g(product)
        if nutritional_list is None:
            continue
        url_page = db.get_url_page(product)
        url_image = db.get_url_image(product)
        if (not url_image):
            continue
        id_product = db.get_id_product(product)
        if (not id_product):
            continue
        id_food = db.get_id_product(product)
        food_search = Food.objects.filter(openff_id=id_food)
        if food_search.exists():
            food_date = food_search.first().last_modified
            last_modified_date = db.get_last_modified(product)
            if last_modified_date != food_date:
                food_search = Food.objects.get(openff_id=id_food)
                Food.objects.filter(openff_id=id_food).update(
                    name=product_name,
                    nutriscore=nutriscore,
                    url=url_page,
                    url_picture=url_image,
                    fat_100g=nutritional_list[0],
                    saturated_fat_100g=nutritional_list[2],
                    sugars_100g=nutritional_list[4],
                    salt_100g=nutritional_list[6],
                    fat_level=nutritional_list[1],
                    salt_level=nutritional_list[7],
                    saturated_fat_level=nutritional_list[3],
                    sugars_level=nutritional_list[5],
                    last_modified=last_modified_date)
                db.get_and_insert_categories_in_db(product, food_search)
                food_search.refresh_from_db()
            else:
                continue
        else:
            food = Food(name=product_name,
                        nutriscore=nutriscore,
                        url=url_page,
                        url_picture=url_image,
                        fat_100g=nutritional_list[0],
                        saturated_fat_100g=nutritional_list[2],
                        sugars_100g=nutritional_list[4],
                        salt_100g=nutritional_list[6],
                        fat_level=nutritional_list[1],
                        salt_level=nutritional_list[7],
                        saturated_fat_level=nutritional_list[3],
                        sugars_level=nutritional_list[5],
                        last_modified=last_modified_date,
                        openff_id=id_product)
            food.save()
            db.get_and_insert_categories_in_db(product, food)
def setup_function(function):
  Food.objects.all.delete()
  cuisine = Cuisine(name="vietnamese")
  cuisine.save()
  restaurant = Restaurant(name="tu lan", location="123 address", cuisine=cuisine)
  restaurant.save()
  food = Food(**{
      "name": "Pho bo",
      "cuisine": cuisine,
      "restaurant": restaurant,
      "price": 8.75,
      "avgRating": 4.5,
      "numRating": 10
    })
  food.save()
def setup_function(function):
  Food.objects.all.delete()
  cuisine = Cuisine(name="vietnamese")
  cuisine.save()
  restaurant = Restaurant(name="tu lan", location="123 address", cuisine=cuisine)
  restaurant.save()
  food = Food(**{
      "name": "Pho bo",
      "cuisine": cuisine,
      "restaurant": restaurant,
      "price": 8.75,
      "avgRating": 4.5,
      "numRating": 10
    })
  food.save()
  function.parametrize(food)
class FoodViewsTest(TestCase):
    """ Class to test views for food application """

    first_food = Food(name="test",
                      nutriscore="a",
                      url="www.off.com",
                      url_picture="www.off.com",
                      fat_100g=0.2,
                      saturated_fat_100g=0.1,
                      sugars_100g=0.7,
                      salt_100g=0.5,
                      fat_level="low",
                      salt_level="low",
                      saturated_fat_level="medium",
                      sugars_level="high",
                      last_modified=datetime(2015, 6, 15),
                      openff_id=125452)

    def test_food_page_template(self):
        """ Test food page template """
        self.first_food.save()
        food = Food.objects.all()
        food_id = food[0].id
        response = self.client.get('/food/%d/' % (food_id))
        self.assertTemplateUsed(response, 'food/food_details.html')
Exemple #7
0
class FoodModelTest(TestCase):
    """ Class for test Food Models """
    def setUp(self):
        """ Executed each test """
        self.first_food = Food(pk=1,
                               name="test",
                               nutriscore="a",
                               url="www.off.com",
                               url_picture="www.off.com",
                               fat_100g=0.2,
                               saturated_fat_100g=0.1,
                               sugars_100g=0.7,
                               salt_100g=0.5,
                               fat_level="low",
                               salt_level="low",
                               saturated_fat_level="medium",
                               sugars_level="high",
                               last_modified=datetime(2015, 6, 15),
                               openff_id=125452)

        self.user = User(pk=1,
                         username="******",
                         first_name="Al",
                         last_name="taga",
                         email="*****@*****.**",
                         password="******")

    def test_saving_and_retrieving_food(self):
        """ test to check if the food is well saved
        and able to retrieve it """
        self.first_food.save()
        saved_food = Food.objects.all()
        self.assertEqual(saved_food.count(), 1)

    def test_link_favorite_food_to_user(self):
        """ Test to see if the favorite food for
        user works """
        self.first_food.save()
        self.user.save()
        food_selected = Food.objects.get(pk=1)
        user_selected = User.objects.get(pk=1)
        food_selected.favorite_users.add(user_selected)
        favorite_added = user_selected.favorite_foods.all()
        self.assertEqual(favorite_added.count(), 1)
Exemple #8
0
    def handle(self, *args, **options):
        self.stdout.write('La base de données se remplie...')
        Food.objects.all().delete()

        for food_choose in foods_choose:
            data_api_openfoodfact = DataApi(food_choose)
            data_products_category = data_api_openfoodfact.select_key_test()

            name_food_nutriscore = \
                data_api_openfoodfact.get_nutriscore_food_choose()
            name_food_category = \
                data_api_openfoodfact.get_categories_name_food()

            name_food = Food(name=food_choose,
                             nutriscore=name_food_nutriscore,
                             category=name_food_category)

            name_food.save()

            for data_product_category in data_products_category:
                name = (data_product_category[0])
                image = (data_product_category[1])
                nutriscore = (data_product_category[2])
                url = (data_product_category[3])
                fat = (data_product_category[4])
                fat_saturated = (data_product_category[5])
                sugar = (data_product_category[6])
                salt = (data_product_category[7])

                food_substitutes = FoodSubstitute(
                    name=name,
                    image=image,
                    nutriscore=nutriscore,
                    url=url,
                    food_id=name_food.pk,
                    nutriments_fat=fat,
                    nutriments_fat_saturated=fat_saturated,
                    nutriments_salt=salt,
                    nutriments_sugars=sugar)
                food_substitutes.save()

        self.stdout.write('Base de données remplie avec succès')
def setup_function(function):
  cuisine = Cuisine(name="vietnamese")
  cuisine.save()
  restaurant = Restaurant(name="tu lan", location="123 address", cuisine=cuisine)
  restaurant.save()
  food = Food(**{
      "name": "Pho bo",
      "cuisine": cuisine,
      "restaurant": restaurant,
      "price": 8.75,
      "avgRating": 4.5,
      "numRating": 10
    })
  food.save()
  image = Image(**{
    "food": food,
    "image": "/images/001.jpg",
    })
  image.save()
  function.parametrize(image);
Exemple #10
0
def search_food(request, foodname):

    food_object = None

    # first check if this food already exists
    for x in Food.objects.all():
        if x.name == foodname:
            food_object = x
            break

    # food already exists
    if food_object is not None:
        return redirect(f'/food/view_food/{food_object.id}')

    # food doesn't exist
    # attempt to get from wolfram alpha api
    nutrients = get_nutrients(foodname)

    if nutrients is None:
        return redirect(f'/food/food_error/{foodname}')

    else:
        # convert the resulting units according to the lookup table
        converted = {}

        # convert to units
        for name, quantity in nutrients.items():
            # convert unit and save
            converted[name] = quantity.to(lookup[reverse_lookup[name]][1]).m

        # create new nutrient
        nutrient = Nutrition(**converted)
        nutrient.save()

        # create new food in database
        food = Food(nutrients=nutrient, name=foodname)
        food.save()

        # go to new page
        return redirect(f'/food/view_food/{food.id}')
Exemple #11
0
def import_food():
    foods = set()
    has_food = Food.objects.values_list('name', flat=True)
    details = open("static/details.json", 'r', encoding='utf-8')
    items = json.load(details)
    for item in items:
        for f in item["foods"]:
            if f["name"] not in has_food:
                foods.add(f["name"])
    create_data = []
    for name in foods:
        create_data.append(Food(name=name, cate_id=46))
    Food.objects.bulk_create(create_data)
Exemple #12
0
def setup_function(function):
    cuisine = Cuisine(name="vietnamese")
    cuisine.save()
    restaurant = Restaurant(name="tu lan",
                            location="123 address",
                            cuisine=cuisine)
    restaurant.save()
    food = Food(
        **{
            "name": "Pho bo",
            "cuisine": cuisine,
            "restaurant": restaurant,
            "price": 8.75,
            "avgRating": 4.5,
            "numRating": 10
        })
    food.save()
    image = Image(**{
        "food": food,
        "image": "/images/001.jpg",
    })
    image.save()
    function.parametrize(image)
Exemple #13
0
    def setUp(self):
        """ Executed each test """
        self.first_food = Food(pk=1,
                               name="test",
                               nutriscore="a",
                               url="www.off.com",
                               url_picture="www.off.com",
                               fat_100g=0.2,
                               saturated_fat_100g=0.1,
                               sugars_100g=0.7,
                               salt_100g=0.5,
                               fat_level="low",
                               salt_level="low",
                               saturated_fat_level="medium",
                               sugars_level="high",
                               last_modified=datetime(2015, 6, 15),
                               openff_id=125452)

        self.user = User(pk=1,
                         username="******",
                         first_name="Al",
                         last_name="taga",
                         email="*****@*****.**",
                         password="******")
Exemple #14
0
def get(request):
    """ dedicated for get methods """
    template_name = 'food/search_page.html'
    query = request.GET.get('search')
    list = Food.get_substitute(query)
    if list is False:
        return render(request, template_name, {'nofood': "Pas d'aliment trouvé"})
    elif list is "error":
        return render(request, template_name, {'no_substitute': "Votre aliment n'a pas de substitut"})
    substitutes_list = list[0]
    paginator = Paginator(substitutes_list, 6)
    page = request.GET.get('page')
    substitutes_list = paginator.get_page(page)
    args = ({'food_search': list[1],
                'articles_found': substitutes_list,
                'image': list[2],
                'page': page,
                'query': query})
    return render(request, template_name, args)
    def handle(self, *args, **kwargs):
        diretory = os.path.join(os.path.dirname(__file__),
                                '../../../feedeasyform_project/assets/')
        jsonfile_path = diretory + 'new_foods.json'

        try:
            with open(jsonfile_path, 'r') as jsonfile:
                foods = json.load(jsonfile)

                for food in foods:
                    name_food_parsed = food.pop('name').replace(' et ', ' & ')

                    try:
                        new_food = Food.objects.get(name=name_food_parsed)
                        state = "modifié dans"
                    except ObjectDoesNotExist:
                        new_food = Food()
                        state = "ajouté à"

                    name_grp_parsed = food.pop('categorie_name').replace(
                        ' et ', ' & ')
                    food.pop('source AJOUT')

                    try:
                        group = FoodGroup.objects.get(name=name_grp_parsed)
                    except ObjectDoesNotExist:
                        group = FoodGroup()
                        group.name = name_grp_parsed
                        group.save()

                    new_food.name = name_food_parsed
                    new_food.id_group = group
                    for k, v in food.items():
                        setattr(new_food, k, v)
                    new_food.save()

                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(name_food_parsed)} {state} la base de données"
                        )

        except Exception as e:
            print(e)
            self.stderr.write(
                self.style.ERROR('Une erreur est survenu. \
\nIl est possible que les ingrédients existe déjà dans la base de données.'))
Exemple #16
0
def fill_table(maxFoodCat, maxFoodPage):
    """
    This function download food and inserting it into
    the local database
    Parameter: maxFoodCat = maximum food categories wished
               maxFoodPage = maximum categories food page wished

    Not all foods are looking for relevant information.
    So we used a table containing the keys searched for
    verification before extraction.
    """

    requiredIndex = ("url", "nutrition_grade_fr",
                     "purchase_places", "manufacturing_places", "countries",
                     "ingredients_text", "product_name", "generic_name_fr",
                     "image_url", "image_small_url",
                     )

    # geting categories objects from openfoodfact
    categoriesUrl = "https://fr.openfoodfacts.org/categories.json"
    r = requests.get(categoriesUrl)
    categories = r.json()

    # insert the categories in the DB
    for i in range(maxFoodCat):
        cat = Category()
        cat.name = categories['tags'][i]['name']
        cat.url = categories['tags'][i]['url']
        cat.save()

        # insert foods for each category
        """
        A category may contain many page of foods, paginate by 20.
        Then we save the differents url in a list tab to loop other
        it and extract any foods that respect the constraint.
        """

        foodPageUrlTab = list()  # the different page url of aliments
        foodPageUrlTab = [cat.url + '/' + str(ind) + '.json'
                          for ind in range(1, maxFoodPage + 1)]

        # request each url of the table to find out the contains foods
        for j in range(len(foodPageUrlTab)):
            foodsUrl = foodPageUrlTab[j]
            r2 = requests.get(foodsUrl)
            foods = r2.json()
            foodsName = list()

            # each page contain 20 foods
            for k in range(len(foods)):
                # verify if the food object keys contain the
                # required index
                if present(requiredIndex, foods['products'][k]):
                    # then add them to the DB
                    food = Food()
                    fObject = foods['products'][k]  # json food object

                    # fill in all the texts fields
                    food.category = cat
                    food.name = fObject['product_name']
                    food.nameFr = fObject['product_name_fr']
                    food.genericNameFr = fObject['generic_name_fr']
                    food.url = fObject['url']
                    food.nutritionGrade = fObject['nutrition_grade_fr']
                    food.manufacturingPlaces = fObject['manufacturing_places']
                    food.purchasePlaces = fObject['purchase_places']
                    food.countries = fObject['countries'].replace("en:", "")
                    food.ingredientsText = fObject['ingredients_text']
                    food.image_link = fObject['image_front_url']

                    # this section deals with uploading images and inserting
                    # them into the DB

                    # we save two kinds of images; small and normal size

                    # variables what store the the saved images directory path
                    #imageDirectory = 'media/image/'  # for the normal size
                    #imageSmallDirectory = 'media/imageSmall/'  # small
                    """imageDirectory = 'media/image/'

                    # variables who rename the downloaded images
                    imageName = "{}.jpg".format(slugify(food.name))
                    imageSmallName = "{}-sm.jpg".format(slugify(food.name))

                    # download the two images with urllib librairy
                    # urllib.request.urlretrieve(imageUrl, localImagePath)
                    imagePath = imageDirectory + str(imageName)
                    imageSmallPath = imageDirectory + str(imageSmallName)

                    urllib.request.urlretrieve(fObject['image_url'],
                                               imagePath)
                    urllib.request.urlretrieve(fObject['image_small_url'],
                                               imageSmallPath)

                    # now we can fill the two imageFields
                    # with the downloaded images
                    food.image = File(open(imagePath, 'rb'))
                    food.imageSmall = File(open(imageSmallPath, 'rb'))"""

                    if food.name in foodsName:
                        pass
                    else:
                        foodsName.append(food.name)
                        food.save()
Exemple #17
0
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

from .forms import SearchForm

from food.models import Food

from haystack.query import SearchQuerySet

categorys = Food.get_food_categorys()


def search(request):
    form = SearchForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        if settings.FULLTEXT_SEARCH is True:
            foods = SearchQuerySet().models(Food).filter(
                content=cd['q']).load_all()
            total_results = foods.count()
        else:
            foods = Food.objects.filter(title__contains=cd['q'])
        return render(request, 'food/list.tpl', {
            'foods': foods,
            'categorys': categorys
        })
    return HttpResponse(status=400)
Exemple #18
0
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

from .forms import SearchForm

from food.models import Food

from haystack.query import SearchQuerySet

categorys = Food.get_food_categorys()

def search(request):
    form = SearchForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        if settings.FULLTEXT_SEARCH is True:
            foods = SearchQuerySet().models(Food).filter(content=cd['q']).load_all()
            total_results = foods.count()
        else:
            foods = Food.objects.filter(title__contains=cd['q'])
        return render(request, 'food/list.tpl', {
                    'foods': foods,
                    'categorys': categorys
                })
    return HttpResponse(status=400)

Exemple #19
0
 def post(self, request):
     try:
         print ">>>request.POST", request.POST
         food_img = request.POST["food_img"]  # 菜图片
         food_price = request.POST["food_price"]  # 菜价格
         food_name = request.POST["food_name"]  # 菜名字
         food_desc = request.POST["food_desc"]  # 活动配图
         group_id = request.POST["group_id"]  # 分组id
         food_id = rand_str(8)
         food = Food()
         food.food_id = food_id
         food.name = food_name
         food.group_id = group_id
         food.food_img = food_img
         food.desc = food_desc
         food.price = food_price
         food.create_time = datetime.now()
         food.save()
         return JsonResponse({"status": 200, "data": request.POST})
     except BaseException, e:
         return JsonResponse({"error": str(e), "status": 400})
Exemple #20
0
def cais(request, response, content):
    if request.method == "GET":  #查询
        if request.GET:
            food_id = request.GET["food_id"]
            f = Food.objects.filter(food_id=food_id).first()
            info = {"name": f.name, "price": str(f.price)}
            content["info"] = info
        else:
            foods = Food.objects.filter(
                is_delete=0, create_time__day=datetime.today().strftime("%d"))
            # foods = Food.objects.filter(is_delete=0,create_time__day="28")
            print ">>>foods: ", foods
            info = [{
                "name": f.name,
                "price": str(f.price),
                "time": f.create_time.strftime("%Y-%m-%d %H:%M:%S")
            } for f in foods]
            content["info"] = info
    elif request.method == "POST":  #添加
        group_id = request.POST["group_id"]
        store_id = request.POST["store_id"]
        name = request.POST["name"]
        desc = request.POST["desc"]
        food_img = request.POST["food_img"]
        price = request.POST["price"]
        sequence = int(request.POST.get("sequence", 1))
        is_delete = int(request.POST.get("is_delete", 0))
        food = Food()
        food.food_id = rand_str(8)
        food.group_id = group_id
        food.store_id = store_id
        food.name = name
        food.desc = desc
        food.food_img = food_img
        food.price = change_money(price)
        food.sequence = sequence
        food.is_delete = is_delete
        food.save()
        content["info"] = {"msg": "成功"}
    elif request.method == "PUT":  #修改
        put = QueryDict(request.body)
        food_id = put["food_id"]
        name = put["name"]
        food = Food.objects.filter(food_id=food_id, is_delete=0).first()
        food.name = name
        food.save()
        info = {"msg": "更新名字成功", "name": name}
        content["info"] = info
    elif request.method == "DELETE":  #删除
        delete = QueryDict(request.body)
        food_id = delete["food_id"]
        food = Food.objects.filter(food_id=food_id, is_delete=0).first()
        food.is_delete = 1
        food.save()
        info = {"msg": "菜删除成功"}
        content["info"] = info
Exemple #21
0
 def test_get_substitutes(self):
     food = Food()
     substitute_list, _, _ = food.get_substitute("test")
     self.assertEqual(len(substitute_list), 1)
Exemple #22
0
 def test_get_substitutes_do_not_find_food(self):
     """ Test to check if the classmethod
     works if there is no food found"""
     food_search = Food.get_substitute("Nutella")
     self.assertEqual(food_search, False)
Exemple #23
0
 def test_get_substitute(self):
     """ Test to find a substitute"""
     substitute_list, _, _ = Food.get_substitute("test2")
     self.assertEqual(len(substitute_list), 2)
Exemple #24
0
    def handle(self, *args, **kwargs):
        diretory = os.path.join(os.path.dirname(__file__),
                                '../../../feedeasyform_project/assets/')
        csvfile_path = diretory + 'table_ingredients.csv'

        try:
            with open(csvfile_path, newline='') as csvfile:
                foods = csv.DictReader(csvfile)

                for food in foods:
                    name_grp_parsed = food['alim_grp_nom_fr'].replace(
                        ' et ', ' & ')
                    try:
                        group = FoodGroup.objects.get(name=name_grp_parsed)

                    except ObjectDoesNotExist:
                        group = FoodGroup()
                        group.name = name_grp_parsed
                        group.save()

                    name_food_parsed = food['alim_nom_fr'].replace(
                        ' et ', ' & ')
                    new_food = Food()
                    new_food.name = name_food_parsed
                    new_food.id_group = group
                    new_food.food_code = food["alim_code"]
                    new_food.proteine = food["Protéines (g/100g)"]
                    new_food.glucide = food["Glucides (g/100g)"]
                    new_food.lipide = food["Lipides (g/100g)"]
                    new_food.sucre = food["Sucres (g/100g)"]
                    new_food.fibre = food["Fibres alimentaires (g/100g)"]
                    new_food.acide_gras_sature = food["AG saturés (g/100g)"]
                    new_food.cholesterol = food["Cholestérol (mg/100g)"]
                    new_food.sel_chlorure_de_sodium = food[
                        "Sel chlorure de sodium (g/100g)"]
                    new_food.calcium = food["Calcium (mg/100g)"]
                    new_food.fer = food["Fer (mg/100g)"]
                    new_food.magnesium = food["Magnésium (mg/100g)"]
                    new_food.potassium = food["Potassium (mg/100g)"]
                    new_food.zinc = food["Zinc (mg/100g)"]
                    new_food.vitamine_c = food["Vitamine C (mg/100g)"]
                    new_food.vitamine_d = food["Vitamine D (µg/100g)"]
                    new_food.vitamine_e = food["Vitamine E (mg/100g)"]
                    new_food.energie = food["Energie (kcal/100g)"]
                    new_food.save()

                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(name_food_parsed)} ajouté à la base de données"
                        )
        except:
            self.stderr.write(
                self.style.ERROR('Une erreur est survenu. \
\nIl est possible que les ingrédients existe déjà dans la base de données.'))
Exemple #25
0
    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"
                    )
Exemple #26
0
 def test_get_substitutes_do_not_have_substitute(self):
     """ Test to check if the classmethod
     works if there is no substitute for
     the product researched"""
     substitute_list, _, _ = Food.get_substitute("test")
     self.assertEqual(len(substitute_list), 1)