コード例 #1
0
ファイル: views.py プロジェクト: khoaanh2212/nextChef
def recipe_pdf(request, slug, id):
    recipe_application_service = RecipeApplicationService.new()
    recipe_id = int(id)
    recipe = get_object_or_404(Recipes, pk=recipe_id)
    allergens = recipe_application_service.get_allergens_for_recipe(recipe.id)
    ingredients = recipe_application_service.get_ingredient_subrecipe_for_recipe(
        recipe.id)
    if recipe.private == 1 and recipe.chef != request.user:
        raise PermissionDenied()

    elif recipe.draft == 1:
        raise PermissionDenied()

    else:
        result = StringIO.StringIO()
        html = render_to_string('recipe/recipe_pdf.html', {
            'recipe': recipe,
            'allergens': allergens,
            'ingredients': ingredients
        }, RequestContext(request))
        pdf = pisa.CreatePDF(html, result)
        result.seek(0)

        if pdf.err:
            raise Http404()

        response = HttpResponse(result, mimetype='application/pdf')
        response['Content-Disposition'] = 'filename=' + str(slug) + '.pdf'
        return response
コード例 #2
0
def add_allergen(request, recipe_id):
    from application.recipe.RecipeApplicationService import RecipeApplicationService
    from recipe.models import Recipes
    from django.http import HttpResponse
    import json

    recipe_application_service = RecipeApplicationService.new()

    try:
        added_allergens = json.loads(request.POST.get("added_allergens"))
        deleted_allergens = json.loads(request.POST.get("deleted_allergens"))

        print(deleted_allergens)

        if added_allergens and isinstance(added_allergens,
                                          list) and len(added_allergens) > 0:
            recipe_application_service.add_custom_allergens(
                recipe_id, added_allergens)

        if deleted_allergens and isinstance(
                deleted_allergens, list) and len(deleted_allergens) > 0:
            recipe_application_service.remove_custom_allergens(
                recipe_id, deleted_allergens)

        return HttpResponse(json.dumps({'success': True}),
                            content_type="application/json")

    except ValueError:
        return HttpResponse('Some thing went wrong',
                            content_type="application/json")
コード例 #3
0
ファイル: ingredients.py プロジェクト: khoaanh2212/nextChef
    def post(self, request, *args, **kwargs):
        try:
            if 'pk' in kwargs:
                raise Http404()

            recipe_application_service = RecipeApplicationService.new()
            data_json = request.body
            data = json.loads(data_json)
            recipe_id = kwargs['recipe_pk']
            costing_ingredient_id = data['costing_ingredient_id']
            is_custom = data['is_custom']
            text = data['text']

            response = recipe_application_service.add_ingredient(
                recipe_id, costing_ingredient_id, is_custom, text,
                request.user)
            return Response(response.to_dto())

        except KeyError:
            return HttpResponse(
                'Invalid argument. Require: costing_ingredient_id, is_custom, text',
                status=400)
        except InvalidRecipeHasIngredientArgumentException, e:
            print(InvalidRecipeHasIngredientArgumentException, e)
            return HttpResponse('Invalid recipe-ingredient exception',
                                status=400)
コード例 #4
0
ファイル: allergen.py プロジェクト: khoaanh2212/nextChef
 def get(self, request, *args, **kwargs):
     if not 'pk' in kwargs:
         raise Http404()
     recipe_id = kwargs['pk']
     recipe_application_service = RecipeApplicationService.new()
     allergens = recipe_application_service.get_allergens_for_recipe(recipe_id)
     return Response(allergens)
コード例 #5
0
ファイル: edamam.py プロジェクト: khoaanh2212/nextChef
 def get(self, request):
     try:
         recipeApplicationService = RecipeApplicationService.new()
         text = request.GET.get('text')
         ingredient = recipeApplicationService.verify_ingredient(text)
         return Response(ingredient.to_dto())
     except InvalidEdamamArgumentException:
         return HttpResponse(status=400)
コード例 #6
0
ファイル: ingredients.py プロジェクト: khoaanh2212/nextChef
    def delete(self, request, *args, **kwargs):

        recipe_ingredient_id = request.GET.get('id')
        recipe_ingredient_id = int(recipe_ingredient_id)

        recipe_application_service = RecipeApplicationService.new()
        recipe_application_service.delete_ingredient(recipe_ingredient_id)

        return HttpResponse(status=200)
コード例 #7
0
ファイル: edamam.py プロジェクト: khoaanh2212/nextChef
    def post(self, request, *args, **kwargs):
        ingredients_json = request.body
        ingredients = json.loads(ingredients_json)

        recipeApplicationService = RecipeApplicationService.new()
        edamamSelectedAllergens = recipeApplicationService.analyzeEdamam(
            ingredients)

        return Response(edamamSelectedAllergens.selected_allergens)
コード例 #8
0
ファイル: subrecipe.py プロジェクト: khoaanh2212/nextChef
    def get(self, request):
        page = request.GET.get('page', 1)
        page = int(page)
        filter = request.GET.get('filter', '')
        chef = request.user

        application_service = RecipeApplicationService.new()
        response = application_service.get_recipe_suggestion_list(chef, filter, page)

        return Response(response)
コード例 #9
0
ファイル: recipes.py プロジェクト: khoaanh2212/nextChef
    def get(self, request, *args, **kwargs):

        if 'pk' not in kwargs:
            raise Http404()

        recipe_id = kwargs['pk']
        recipe_application_service = RecipeApplicationService.new()

        ingredient_subrecipe = recipe_application_service.get_ingredient_subrecipe_for_recipe(
            recipe_id)
        allergens = recipe_application_service.get_allergens_for_recipe(
            recipe_id)
        return Response({
            "ingredients": ingredient_subrecipe,
            "allergens": allergens
        })
コード例 #10
0
def following(request, activation_complete=False):
    recipes = Recipes.objects.search_explore(request.user, hide_for_sale=True)[:30]
    serializer = ApiV1ExploreRecipeSerializer(recipes, many=True)
    explore_page = dict(recipes=serializer.data)
    recipes_json = json.dumps(explore_page)
    header_recipes = Recipes.objects.explore_header_recipes()

    recipeAppService = RecipeApplicationService.new()
    recipeInPublicBooks = recipeAppService.get_recipe_by_following_chef(request.user)

    response = dict(
        explore_page=recipes_json,
        activation_complete=activation_complete,
        header_recipes=header_recipes,
        SECTION='FOLLOWING',
        recipeInPublicBooks=json.dumps(recipeInPublicBooks)
    )
    return render_to_response('explore/explore.html', response, context_instance=RequestContext(request))
コード例 #11
0
ファイル: subrecipe.py プロジェクト: khoaanh2212/nextChef
    def post(self, req):

        json_data = req.body
        data = json.loads(json_data)

        try:

            recipe_id = data['recipe_id']
            subrecipe_id = data['subrecipe_id']
            amount = data['amount']
            application_service = RecipeApplicationService.new()
            subrecipe = application_service.add_subrecipe(recipe_id, subrecipe_id, amount)
            return Response(subrecipe.to_dto())

        except KeyError:
            return HttpResponse('Invalid Argument', status=400)
        except Recipes.DoesNotExist:
            return HttpResponse('Invalid Recipe', status=400)
        except InvalidRecipeHasSubrecipeArgumentException:
            return HttpResponse('Recipe cannot be added to itself', status=400)
コード例 #12
0
    def setUp(self):
        self.recipe_service_stub = mock.Mock()
        self.edamam_service_stub = mock.Mock()
        self.book_service_stub = mock.Mock()
        self.costing_ingredient_service_stub = mock.Mock()
        self.recipe_ingredient_service_stub = mock.Mock()
        self.recipe_subrecipe_service_stub = mock.Mock()
        self.recipe_wrapper_stub = mock.Mock()
        self.recipe_permission_view_repo_stub = mock.Mock()
        self.custom_changes_ingredient_service_stub = mock.Mock()

        self.sut = RecipeApplicationService.new(
            recipe_service=self.recipe_service_stub,
            edamam_service=self.edamam_service_stub,
            book_service=self.book_service_stub,
            custom_changes_ingredient_service=self.
            custom_changes_ingredient_service_stub,
            costing_ingredient_service=self.costing_ingredient_service_stub,
            recipe_ingredient_service=self.recipe_ingredient_service_stub,
            recipe_subrecipe_service=self.recipe_subrecipe_service_stub,
            recipe_wrapper=self.recipe_wrapper_stub,
            recipe_permission_view_repo=self.recipe_permission_view_repo_stub)
コード例 #13
0
ファイル: views.py プロジェクト: khoaanh2212/nextChef
def recipe(request, slug, id):
    recipe_application_service = RecipeApplicationService.new()
    book_application_service = BookApplicationService.new()
    # Sanitize input, if we don't get id redirect permanent to home page
    try:
        recipe_id = int(id)
        cache = get_cache('default')
        recipe_key = CacheUtils.get_key(CacheUtils.RECIPE, recipe_id=recipe_id)
        recipe = cache.get(recipe_key, None)
        if recipe is None:
            recipe = Recipes.objects.select_related('chef').get(id=recipe_id)
            cache.set(recipe_key, recipe)
    except (ValueError, Recipes.DoesNotExist):
        raise Http404()

    is_chef_or_collaborator = False

    if not recipe_application_service.is_recipe_available_for_chef(
            recipe.id, request.user.id):

        if request.user.is_authenticated():
            allowed = False
            chef_added_book_ids = request.user.books_added.all().values_list(
                'id', flat=True)
            recipe_book_ids = BookHasRecipes.objects.filter(
                recipe=recipe).values_list('book', flat=True)
            for chef_added_book_id in chef_added_book_ids:
                if chef_added_book_id in recipe_book_ids:
                    allowed = True
                    break
            if not allowed:
                raise PermissionDenied()
        else:
            raise PermissionDenied()
    elif recipe.draft == 1 and recipe.chef != request.user:
        raise PermissionDenied()

    elif recipe.draft == 1 and recipe.chef == request.user:
        return HttpResponseRedirect(
            reverse('kitchen_draft', kwargs={'id': recipe.id}))

    # Hide the sections of the page that you will see after you pay
    hide_to_sell = False

    # Hide the sections of the page of a normal recipe
    book_to_sell_recipe = False

    book_to_sell = None
    chef_has_book = None
    book_to_sell_has_recipes = []

    if not request.GET.has_key('view') and not request.GET.get(
            'view') == 'premium':
        books = BookHasRecipes.objects.filter(recipe=recipe,
                                              book__book_type=Book.TO_SELL)
        if books.exists():
            book_to_sell = books[0].book
            book_to_sell_recipe = True
            hide_to_sell = True

            book_to_sell_has_recipes = BookHasRecipes.objects.filter(
                book=book_to_sell)  # .exclude(recipe=recipe)
            if request.user.is_authenticated():
                try:
                    chef_has_book = ChefsHasBooks.objects.get(
                        chef=request.user, book=book_to_sell)
                    hide_to_sell = False
                except:
                    pass

    recipe_cover_key = CacheUtils.get_key(CacheUtils.RECIPE_COVER,
                                          recipe_id=recipe_id)
    recipe_cover = cache.get(recipe_cover_key, None)
    if recipe_cover is None:
        recipe_cover = thumbnail_url(recipe.cover, 'explore_cover')
        cache.set(recipe_cover_key, recipe_cover)

    recipe_steps_key = CacheUtils.get_key(CacheUtils.RECIPE_STEPS,
                                          recipe_id=recipe_id)
    recipe_steps = cache.get(recipe_steps_key, None)
    if recipe_steps is None:
        recipe_steps = []
        for step in recipe.photos.all():
            step_thumb_small = thumbnail_url(step.image, 'recipe_step')
            step_thumb_big = thumbnail_url(step.image, 'recipe_step_full_size')
            recipe_steps.append(
                dict(
                    instructions=step.instructions,
                    photo_order=step.photo_order,
                    step_thumb_small=step_thumb_small,
                    step_thumb_big=step_thumb_big,
                ))
        cache.set(recipe_steps_key, recipe_steps)

    recipe_ingredients_key = CacheUtils.get_key(CacheUtils.RECIPE_INGREDIENTS,
                                                recipe_id=recipe_id)
    recipe_ingredients = cache.get(recipe_ingredients_key, None)
    if recipe_ingredients is None:
        recipe_ingredients = recipe.get_sorted_ingredients()
        cache.set(recipe_ingredients_key, recipe_ingredients)

    recipe_tags_keys = CacheUtils.get_key(CacheUtils.RECIPE_TAGS,
                                          recipe_id=recipe_id)
    recipe_tags = cache.get(recipe_tags_keys, None)
    if recipe_tags is None:
        recipe_tags = recipe.tags.all()
        cache.set(recipe_tags_keys, recipe_tags)

    recipe_comments_key = CacheUtils.get_key(CacheUtils.RECIPE_COMMENTS,
                                             recipe_id=recipe_id)
    recipe_comments = cache.get(recipe_comments_key, None)
    if recipe_comments is None:
        recipe_comments = recipe.comments.select_related('chef').all()
        cache.set(recipe_comments_key, recipe_comments)

    recipe_products_key = CacheUtils.get_key(CacheUtils.RECIPE_PRODUCTS,
                                             recipe_id=recipe_id)
    recipe_products = cache.get(recipe_products_key, None)
    if recipe_products is None:
        recipe_products = recipe.products.all()
        cache.set(recipe_products_key, recipe_products)

    chef = recipe.chef
    other_recipes = recipe_application_service.get_recipes_for_explore(
        request.user)[:4]
    print(other_recipes)

    chef_followings_key = CacheUtils.get_key(
        CacheUtils.CHEF_FOLLOWINGS_LIST_10, chef_id=chef.id)
    chef_followings = cache.get(chef_followings_key, None)
    if chef_followings is None:
        temp_followings = chef.following.all()[:10]
        serializer = LibraryChefSerializer(temp_followings, many=True)
        temp_serialized = serializer.data
        cache.set(chef_followings_key, temp_serialized)
        chef_followings = temp_serialized[:4]
    else:
        chef_followings = chef_followings[:4]

    chef_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_AVATAR,
                                         chef_id=chef.id)
    chef_avatar = cache.get(chef_avatar_key, None)
    if chef_avatar is None:
        if chef.avatar:
            chef_avatar = thumbnail_url(chef.avatar, 'chef_avatar')
            cache.set(chef_avatar_key, chef_avatar)

    site = Site.objects.get_current()

    user_books_json = []
    recipe_in_books_json = []
    related_recipes = []
    show_private = False
    if request.user.is_authenticated():
        user_books_json = None
        recipe_in_books_json = None
        if user_books_json is None:
            user_books = request.user.books.all()
            user_books_json = json.dumps(
                WebRecipeBookSerializer(user_books).data)

        if recipe_in_books_json is None:
            recipe_in_books = BookHasRecipes.objects.values_list(
                'book_id', flat=True).filter(recipe=recipe,
                                             book__chef=request.user)
            recipe_in_books_json = []
            for rib in recipe_in_books:
                recipe_in_books_json.append(rib)
            recipe_in_books_json = json.dumps(recipe_in_books_json)

            # related_recipes_key = CacheUtils.get_key(CacheUtils.CHEF_RELATED_RECIPES_5, chef_id=chef.id)
            # related_recipes = cache.get(related_recipes_key, None)
            # if related_recipes is None:
            #     chef = recipe.chef
            #     show_private = chef == request.user
            #     books = Book.objects.all_books(chef, show_private=show_private)
            #     related_recipes = recipe_application_service.get_recipe_by_books(books)
            #     cache.set(related_recipes_key, related_recipes)

        chef = recipe.chef

        show_private = chef == request.user

        if chef == request.user:
            books = book_application_service.get_book_by_chef(chef)
        else:
            books = Book.objects.all_books(chef, show_private=show_private)
            collaborated_books = book_application_service.getBooksByCollaborator(
                chef, request.user) if request.user.id else list()
            books = list(chain(books, collaborated_books))
            books = list(set(books))

        related_recipes = recipe_application_service.get_visible_recipes(
            request.user.id, chef.id)

    try:
        chef = Chefs.objects.get(pk=chef.id)
    except:
        chef = chef

    is_collaborator = book_application_service.check_chef_is_collaborator_of_recipe(
        request.user, recipe)
    allergens = recipe_application_service.get_allergens_for_recipe(recipe.id)
    if chef == request.user or is_collaborator:
        is_chef_or_collaborator = True
    else:
        is_chef_or_collaborator = False

    allow_see_pricing = False
    if request.user.is_authenticated() and (
            request.user.membership == 'default'
            or request.user.membership == 'pro'):
        allow_see_pricing = False
    else:
        allow_see_pricing = True

    response = dict(
        recipe=recipe,
        chef=chef,
        hide_to_sell=hide_to_sell,
        book_to_sell=book_to_sell,
        book_to_sell_recipe=book_to_sell_recipe,
        book_to_sell_has_recipes=book_to_sell_has_recipes,
        chef_has_book=chef_has_book,
        chef_avatar=chef_avatar,
        recipe_cover=recipe_cover,
        recipe_steps=recipe_steps,
        recipe_ingredients=recipe_ingredients,
        recipe_tags=recipe_tags,
        recipe_comments=recipe_comments,
        recipe_products=recipe_products,
        related_recipes=related_recipes,
        chef_followings=chef_followings,
        other_recipes=other_recipes,
        SITE=site,
        user_books=user_books_json,
        recipe_in_books=recipe_in_books_json,
        is_chef_or_collaborator=is_chef_or_collaborator,
        allow_see_pricing=allow_see_pricing,
        owner=show_private,
        allergens=allergens,
    )
    return render_to_response('recipe/recipe.html',
                              response,
                              context_instance=RequestContext(request))
コード例 #14
0
ファイル: views.py プロジェクト: khoaanh2212/nextChef
def library(request, slug, id):
    try:
        chef_id = int(id)
    except ValueError:
        raise Http404()

    recipe_application_service = RecipeApplicationService.new()
    book_application_service = BookApplicationService.new()

    cache = get_cache('default')
    chef_key = CacheUtils.get_key(CacheUtils.CHEF, chef_id=chef_id)
    chef = get_object_or_404(Chefs, pk=chef_id)
    if not chef.is_active:
        raise Http404
    cache.set(chef_key, chef)

    restaurant_key = CacheUtils.get_key(CacheUtils.CHEF_RESTAURANT,
                                        chef_id=chef_id)
    restaurant = cache.get(restaurant_key, None)
    if restaurant is None:
        restaurants = Restaurant.objects.filter(chef=chef.id)
        if restaurants.exists():
            restaurant = restaurants[0]
            cache.set(restaurant_key, restaurant)
        else:
            # per no fer la consulta Restaurant.object en cas que no estigui cachejat perque no existeix
            cache.set(restaurant_key, -1)
            restaurant = -1

    profile_form = None
    restaurant_form = None
    social_form = None
    message_content = ''
    message_type = None
    if request.user == chef:
        if request.method == 'POST':
            profile_form = EditChefForm(request.POST, instance=chef)
            if profile_form.is_valid():
                saved_instance = profile_form.save(commit=True)
                if saved_instance.email_newsletter == True:
                    EmailingList.objects.subscribe_chef(saved_instance)
                else:
                    EmailingList.objects.unsubscribe_chef(saved_instance)
            # update new pasword
            if request.POST['isChangePassword'] == '1':
                if (chef.check_password(request.POST['old_password'])):
                    chef.set_password(request.POST['new_password'])
                    chef.save()
                    message_content = 'The password has been changed successfully'
                    message_type = 'success'
                else:
                    message_content = 'The password has not been changed. Please try again.'
                    message_type = 'danger'
            else:
                message_content = ''
                message_type = None

            if restaurant != -1:
                restaurant_form = EditRestaurantForm(request.POST,
                                                     instance=restaurant,
                                                     prefix="restaurant")
                if restaurant_form.is_valid():
                    rest_instance = restaurant_form.save(commit=False)
                    rest_instance.latitude = restaurant_form.cleaned_data[
                        'latitude']
                    rest_instance.longitude = restaurant_form.cleaned_data[
                        'longitude']
                    rest_instance.save()
                    cache.set(restaurant_key, rest_instance)
            else:
                restaurant_form = EditRestaurantForm(request.POST,
                                                     prefix="restaurant")
                if restaurant_form.is_valid():
                    rest_instance = restaurant_form.save(commit=False)
                    rest_instance.chef = chef
                    rest_instance.latitude = 0
                    rest_instance.longitude = 0
                    rest_instance.save()
                    cache.set(restaurant_key, rest_instance)

            social_form = EditSocialForm(request.POST, instance=chef)
            if social_form.is_valid():
                social_form.save(commit=True)
            cache.set(chef_key, chef)
        else:
            profile_form = EditChefForm(instance=chef)
            if restaurant != None and restaurant != -1:
                restaurant_form = EditRestaurantForm(instance=restaurant,
                                                     prefix="restaurant")
            else:
                restaurant_form = EditRestaurantForm(prefix="restaurant")
            social_form = EditSocialForm(instance=chef)

    # DISABLED CACHE ON LIBRARY
    # if request.user == chef:
    #     books_key = CacheUtils.get_key(CacheUtils.CHEF_ALL_BOOKS, chef_id=chef_id)
    # else:
    #     books_key = CacheUtils.get_key(CacheUtils.CHEF_PUBLIC_BOOKS, chef_id=chef_id)
    # books_json = cache.get(books_key, None)
    #
    # books_list = []
    # if books_json is not None:
    #     books_list = json.loads(books_json)
    #
    # if not books_list:
    #     show_private = chef == request.user
    #     books = Book.objects.all_books(chef, show_private=show_private)
    #     books_serializer = WebBookSerializer(books)
    #     books_json = json.dumps(books_serializer.data)

    show_private = chef == request.user
    if chef == request.user:
        books = book_application_service.get_book_by_chef(chef)
    else:
        books = Book.objects.all_books(chef, show_private=show_private)
        collaborated_books = book_application_service.getBooksByCollaborator(
            chef, request.user) if request.user.id else list()
        books = list(chain(books, collaborated_books))
        books = list(set(books))

    books_serializer = WebBookSerializer(books)
    books_json = json.dumps(books_serializer.data)

    # END DISABLED

    drafts_key = CacheUtils.get_key(CacheUtils.CHEF_DRAFTS, chef_id=chef_id)
    drafts_json = []
    if request.user == chef:
        drafts_json = cache.get(drafts_key, None)
        if drafts_json is None:
            drafts = chef.recipes.filter(
                chef=chef,
                draft=True).select_related('chef').order_by('-creation_date')
            drafts_serializer = WebRecipeSerializer(drafts)
            drafts_json = json.dumps(drafts_serializer.data)
            cache.set(drafts_key, drafts_json)

    if request.user == chef:
        recipes_count_key = CacheUtils.get_key(
            CacheUtils.CHEF_PRIVATE_RECIPES_COUNT, chef_id=chef_id)
        recipes_count = cache.get(recipes_count_key, None)
    else:
        recipes_count_key = CacheUtils.get_key(
            CacheUtils.CHEF_PUBLIC_RECIPES_COUNT, chef_id=chef_id)
        recipes_count = cache.get(recipes_count_key, None)

    if recipes_count is None:
        recipes_count = 0

    if request.user == chef:
        # recipes_key = CacheUtils.get_key(CacheUtils.CHEF_PRIVATE_RECIPES_12_PAGE1, chef_id=chef.id)
        recipes = recipe_application_service.get_recipe_by_books(books)
        recipes_count = len(recipes)
        recipes_12 = recipes[:12]
        recipes_serializer = WebRecipeSerializer(recipes_12)
        recipes_json = json.dumps(recipes_serializer.data)
        # recipes_json = cache.get(recipes_key, None)
        # if recipes_json is None:
        # recipes = Recipes.objects.get_recipes_by_chef(chef_id, private=1)
        # recipes = recipe_application_service.get_recipe_by_books(books)
        # recipes_count = len(recipes)
        # recipes_12 = recipes[:12]
        # recipes_serializer = WebRecipeSerializer(recipes_12)
        # recipes_json = json.dumps(recipes_serializer.data)
        # cache.set(recipes_key, recipes_json)
        # cache.set(recipes_count_key, recipes_count)
    else:
        recipes = recipe_application_service.get_recipe_by_books(books)
        recipes_count = len(recipes)
        recipes_12 = recipes[:12]
        recipes_serializer = WebRecipeSerializer(recipes_12)
        recipes_json = json.dumps(recipes_serializer.data)
        # recipes_key = CacheUtils.get_key(CacheUtils.CHEF_PUBLIC_RECIPES_12_PAGE1, chef_id=chef.id)
        # recipes_json = cache.get(recipes_key, None)
        # if recipes_json is None:
        #     recipes = recipe_application_service.get_recipe_by_books(books)
        #     recipes_count = len(recipes)
        #     recipes_12 = recipes[:12]
        #     recipes_serializer = WebRecipeSerializer(recipes_12)
        #     recipes_json = json.dumps(recipes_serializer.data)
        #     cache.set(recipes_key, recipes_json)
        #     cache.set(recipes_count_key, recipes_count)

    chef_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_AVATAR,
                                         chef_id=chef.id)
    chef_avatar = cache.get(chef_avatar_key, None)
    if chef_avatar is None:
        if chef.avatar:
            chef_avatar = thumbnail_url(chef.avatar, 'chef_avatar')
            cache.set(chef_avatar_key, chef_avatar)

    chef_base_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_BASE_NAV_AVATAR,
                                              chef_id=chef.id)
    chef_base_avatar = cache.get(chef_base_avatar_key, None)
    if chef_base_avatar is None:
        if chef.avatar:
            chef_base_avatar = thumbnail_url(chef.avatar, 'base_nav_avatar')
            cache.set(chef_base_avatar_key, chef_base_avatar)

    chef_cover_key = CacheUtils.get_key(CacheUtils.CHEF_COVER, chef_id=chef_id)
    chef_cover = cache.get(chef_cover_key, None)
    if chef_cover is None or chef_cover == '':
        if chef.cover:
            chef_cover = thumbnail_url(chef.cover, 'library_cover')
            cache.set(chef_cover_key, chef_cover)
        elif chef.best_recipe:  # si no hi ha cover, agafa la best_recipe
            chef_cover = thumbnail_url(chef.best_recipe.cover, 'library_cover')
            cache.set(chef_cover_key, chef_cover)

    chef_edit_cover = None
    if request.user == chef:
        chef_edit_cover_key = CacheUtils.get_key(CacheUtils.CHEF_EDIT_COVER,
                                                 chef_id=chef_id)
        chef_edit_cover = cache.get(chef_edit_cover_key, None)
        if chef_edit_cover is None or chef_cover == '':
            if chef.cover:
                chef_edit_cover = thumbnail_url(chef.cover,
                                                'library_edit_modal_cover')
                cache.set(chef_edit_cover_key, chef_edit_cover)
            elif chef.best_recipe:
                chef_edit_cover = thumbnail_url(chef.best_recipe.cover,
                                                'library_edit_modal_cover')
                cache.set(chef_edit_cover_key, chef_edit_cover)

    chef_followings_count_key = CacheUtils.get_key(
        CacheUtils.CHEF_FOLLOWINGS_COUNT, chef_id=chef.id)
    chef_following_count = cache.get(chef_followings_count_key, None)
    if chef_following_count is None:
        chef_following_count = chef.following.count()
        cache.set(chef_followings_count_key, chef_following_count)

    chef_followers_count_key = CacheUtils.get_key(
        CacheUtils.CHEF_FOLLOWERS_COUNT, chef_id=chef.id)
    chef_followers_count = cache.get(chef_followers_count_key, None)
    if chef_followers_count is None:
        chef_followers_count = chef.followers.count()
        cache.set(chef_followers_count_key, chef_followers_count)

    restaurant_image = None
    if restaurant is not -1:
        restaurant_image_key = CacheUtils.get_key(
            CacheUtils.CHEF_RESTAURANT_IMAGE, chef_id=chef.id)
        restaurant_image = cache.get(restaurant_image_key, None)
        if restaurant_image is None:
            if restaurant.image:
                restaurant_image = thumbnail_url(restaurant.image,
                                                 'library_restaurant_cover')
                cache.set(restaurant_image_key, restaurant_image)

    is_at_home = chef == request.user
    if request.user == chef:
        type_member = get_type_of_member(request)
    else:
        type_member = None
    response = dict(chef=chef,
                    books=books_json,
                    recipes=recipes_json,
                    recipes_count=recipes_count,
                    drafts=drafts_json,
                    profile_form=profile_form,
                    restaurant_form=restaurant_form,
                    social_form=social_form,
                    restaurant=restaurant,
                    chef_avatar=chef_avatar,
                    chef_cover=chef_cover,
                    chef_following_count=chef_following_count,
                    chef_followers_count=chef_followers_count,
                    restaurant_image=restaurant_image,
                    chef_base_avatar=chef_base_avatar,
                    chef_edit_cover=chef_edit_cover,
                    is_at_home=is_at_home,
                    type_member=type_member,
                    message_content=message_content,
                    message_type=message_type)
    return render_to_response('library/library.html',
                              response,
                              context_instance=RequestContext(request))
コード例 #15
0
def recommended(request, activation_complete=False, nux=False):

    # NUX CONFIGURATION
    if request.method == 'POST':
        is_foodie = request.POST.get('type', 'true')
        following_array = request.POST.get('chefs', '')
        following_array = following_array.split(',')
        user = request.user
        if is_foodie == 'true':
            user.type = 0
        else:
            user.type = 1

        for chef_id in following_array:
            chef = Chefs.objects.get(pk=chef_id)
            user.follow(chef)
        user.save()

        cache = get_cache('default')
        # chef looses or adds followers count
        key = CacheUtils.get_key(CacheUtils.CHEF_FOLLOWERS_COUNT, chef_id=chef_id)
        cache.set(key, None)
        # chef looses or adds followings in list
        key = CacheUtils.get_key(CacheUtils.CHEF_FOLLOWINGS_LIST_10, chef_id=chef_id)
        cache.set(key, None)
        # chef looses or adds followers in list
        key = CacheUtils.get_key(CacheUtils.CHEF_FOLLOWERS_LIST_10, chef_id=chef_id)
        cache.set(key, None)
        # user looses or adds to who is followings count
        key = CacheUtils.get_key(CacheUtils.CHEF_FOLLOWINGS_COUNT, chef_id=request.user.id)
        cache.set(key, None)
        # user looses or adds to who is following
        key = CacheUtils.get_key(CacheUtils.USER_FOLLOWINGS, user_id=request.user.id)
        cache.set(key, None)

        return HttpResponseRedirect(reverse('home'))

    view = RecipeRecommendedView.as_view()
    recipeAppService = RecipeApplicationService.new()
    recipeInPublicBooks = recipeAppService.get_all_public_recipes()
    request.GET = request.GET.copy()
    request.GET['web'] = '1'
    nux_chefs = []
    if nux:
        queryset = Chefs.objects.filter(onboard_score__gt=0)
        lang = request.LANGUAGE_CODE.split('-')[0]
        if lang in request.user.LANGUAGES_CHOICES:
            queryset = queryset.filter(onboard_languages__contains=lang)
            if queryset.count() < 5:
                queryset = queryset.filter(onboard_languages__contains='en')
        else:
            queryset = queryset.filter(onboard_languages__contains='en')
        nux_chefs = queryset.order_by('?')[:10]

    header_recipes = Recipes.objects.explore_header_recipes()
    response = dict(
        explore_page=json.dumps(view(request).data),
        activation_complete=activation_complete,
        header_recipes=header_recipes,
        nux=nux,
        nux_chefs=nux_chefs,
        SECTION='RECOMMENDED',
        recipeInPublicBooks=json.dumps(recipeInPublicBooks)
    )
    return render_to_response('explore/explore.html', response, context_instance=RequestContext(request))