def delete(request, id): try: recipe_id = int(id) recipe = get_object_or_404(Recipes, pk=recipe_id) if recipe.chef == request.user: recipe.delete() cache = get_cache('default') keys = CacheUtils.refresh_recipe(CacheUtils(), recipe_id=recipe_id, chef_id=recipe.chef.id) for key in keys: cache.set(key, None) return HttpResponseRedirect( reverse('library', kwargs={ 'slug': request.user.slug, 'id': request.user.id })) return HttpResponseForbidden() except ValueError: raise Http404()
def post(self, request, book_id, recipe_id): try: from django.db.models import get_model model_class = get_model('books', 'Book') book = model_class.objects.get(pk=book_id) if request.user != book.chef: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) recipe = Recipes.objects.get(id=recipe_id) if recipe.chef != book.chef and \ not ChefsHasRecipes.objects.filter(chef=book.chef, recipe=recipe).exists(): ChefsHasRecipes.objects.create(chef=book.chef, recipe=recipe) Notification.create_new_copy_recipe(recipe, book.chef) if not book.has_recipe(recipe): book.add_recipe(recipe) # Events.track(request.user.email, Events.EVENT_RECIPE_TO_BOOK) cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.CHEF_BOOKS, chef_id=request.user.id) cache.set(key, None) return Response({ 'success': True, 'added': True }, status=status.HTTP_200_OK) else: book.delete_recipe(recipe) cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.CHEF_BOOKS, chef_id=request.user.id) cache.set(key, None) return Response({ 'success': True, 'added': False }, status=status.HTTP_200_OK) except: return Response({ 'success': False, }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, recipe_id): try: if request.user.is_authenticated(): recipe = Recipes.objects.get(pk=recipe_id) loves = Likes.objects.filter(recipe=recipe, chef=request.user) if loves.exists(): love = loves[0] love.delete() loved = False Events.track(request.user.email, Events.EVENT_UNLOVE) else: Likes.objects.create(recipe=recipe, chef=request.user, creation_date=datetime.datetime.now()) loved = True Events.track(request.user.email, Events.EVENT_LOVE) recipe.update_likes() cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_LOVES, user_id=request.user.id) cache.set(key, None) return Response({ 'success': True, 'loved': loved }, status=status.HTTP_200_OK) else: return Response({'success': False}, status=status.HTTP_403_FORBIDDEN) except Exception: return Response({'success': False}, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, chef_id): try: chef = Chefs.objects.get(id=chef_id) if chef != request.user: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) restaurant, created = Restaurant.objects.get_or_create(chef=chef) restaurant.image = request.FILES['image'] restaurant.save() cache = get_cache('default') restaurant_image_key = CacheUtils.get_key( CacheUtils.CHEF_RESTAURANT_IMAGE, chef_id=chef_id) restaurant_image = thumbnail_url(restaurant.image, 'library_restaurant_cover') cache.set(restaurant_image_key, restaurant_image) return Response({ 'success': True, 'url': restaurant.thumb_account_button }) except Exception, e: return Response({ 'success': False, 'error': e }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, book_id): try: book = Book.objects.get(pk=book_id) if book.chef != request.user: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) new_name = str(request.POST.get('name', '')) new_private = int(request.POST.get('private', 0)) new_collaborators = str(request.POST.get('collaborators', '')) book_application_service = BookApplicationService.new() new_collaborator_ids = book_application_service.decorate_collaborators( new_collaborators) book_application_service.send_email_collaborator_when_edit( book.collaborators, new_collaborator_ids, book, request) book.name = new_name book.private = new_private book.collaborators = new_collaborators book.save() cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.CHEF_BOOKS, chef_id=request.user.id) cache.set(key, None) return Response({'success': True}, status=status.HTTP_200_OK) except: return Response({'success': False}, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, recipe_id): try: recipe = Recipes.objects.get(pk=recipe_id) if recipe.chef != request.user: return Response({'success': False}, status=status.HTTP_403_FORBIDDEN) data_json = request.body data = json.loads(data_json) grossProfit = data['grossProfit'] foodCost = data['foodCost'] vat = data['vat'] serves = int(data['serves']) serves_proportion = float(serves) / recipe.serves recipe_has_ingredient_service = RecipeHasIngredientService.new() recipe_has_ingredient_service.updateRecipeHasIngredientWhenChangeServes( serves_proportion, recipe.id) recipe.gross_profit = grossProfit recipe.food_cost = foodCost recipe.vat = vat recipe.serves = serves recipe.save() cache = get_cache('default') recipe_key = CacheUtils.get_key(CacheUtils.RECIPE, recipe_id=recipe_id) cache.set(recipe_key, recipe) return Response({'success': True}, status=status.HTTP_200_OK) except: return Response({'success': False}, status=status.HTTP_400_BAD_REQUEST)
def congratulations(request, id): recipe_id = int(id) recipe = Recipes.objects.select_related('chef').get(id=recipe_id) if recipe.chef != request.user: # or recipe.publication_date != None: return HttpResponseForbidden() recipe.publication_date = datetime.datetime.now() recipe.save() cache_utils = CacheUtils() cache_utils.reset_chef_cache(request.user.id) site = RequestSite(request) try: from django.conf import settings from premailer import transform from django.template.loader import render_to_string from books.models import BookHasRecipes from django.core.mail.message import EmailMultiAlternatives books = BookHasRecipes.objects.filter(book__chef=recipe.chef, recipe=recipe) email_data = dict(user=request.user, recipe=recipe, books=books, site=site) mail = render_to_string('recipe/publish_email.html', email_data) inlined_mail = transform(mail) mail = EmailMultiAlternatives( recipe.name + ', the photorecipe', '', settings.SERVER_EMAIL, [ request.user.email, ], ) mail.attach_alternative(inlined_mail, 'text/html') mail.send(fail_silently=True) except: pass response = dict(recipe=recipe, SITE=site) return render_to_response('kitchen/congratulations.html', response, context_instance=RequestContext(request))
def collections(context): cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.COLLECTIONS) colls = cache.get(key, None) if colls is None: colls = Collection.objects.filter(is_active=True).order_by('name') cache.set(key, colls) return {'COLLECTIONS': colls}
def post(self, request, chef_id): try: chef = Chefs.objects.get(id=chef_id) if chef != request.user: return Response({'success': False}, status=status.HTTP_403_FORBIDDEN) photo, created = Photos.objects.get_or_create(chef=chef) photo.image_url = request.FILES['image'] photo.save() photo.s3_url = photo.image_url.url # Ensure same value as image_url photo.save() cache = get_cache('default') chef_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_AVATAR, chef_id=chef_id) 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 = thumbnail_url(chef.avatar, 'base_nav_avatar') cache.set(chef_base_avatar_key, chef_base_avatar) if chef == request.user: avatar_key = CacheUtils.get_key(CacheUtils.USER_AVATAR, user_id=chef_id) avatar = thumbnail_url(photo.image_url, 'base_nav_avatar') cache.set(avatar_key, avatar) return Response({ 'success': True, 'url': chef.avatar_thumb('chef_avatar') }) except Exception, e: return Response({ 'success': False, 'error': e }, status=status.HTTP_400_BAD_REQUEST)
def user_avatar(request): avatar = None if request.user.is_authenticated(): cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_AVATAR, user_id=request.user.id) avatar = cache.get(key, None) if avatar is None: avatar = thumbnail_url(request.user.avatar, 'base_nav_avatar') cache.set(key, avatar) return {'USER_AVATAR': avatar}
def user_loves(request): user_loves_json = [] if request.user.is_authenticated(): cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_LOVES, user_id=request.user.id) user_loves_json = cache.get(key, None) if user_loves_json is None: user_loves_json = json.dumps(request.user.loves_list) cache.set(key, user_loves_json) return {'USER_LOVES_LIST': user_loves_json}
def user_followings(request): user_followings_json = [] if request.user.is_authenticated(): cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_FOLLOWINGS, user_id=request.user.id) user_followings_json = cache.get(key, None) if user_followings_json is None: user_followings_json = json.dumps(request.user.follows_list) cache.set(key, user_followings_json) return {'USER_FOLLOWINGS_LIST': user_followings_json}
def post(self, request, chef_id): try: chef = Chefs.objects.get(id=chef_id) if chef != request.user: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) chef.cover = request.FILES['image'] chef.save() cache = get_cache('default') chef_cover_key = CacheUtils.get_key(CacheUtils.CHEF_COVER, chef_id=chef_id) chef_cover = thumbnail_url(chef.cover, 'library_cover') cache.set(chef_cover_key, chef_cover) chef_edit_cover_key = CacheUtils.get_key( CacheUtils.CHEF_EDIT_COVER, chef_id=chef_id) chef_edit_cover = thumbnail_url(chef.cover, 'library_edit_modal_cover') cache.set(chef_edit_cover_key, chef_edit_cover) chef_key = CacheUtils.get_key(CacheUtils.CHEF, chef_id=chef_id) cache.set(chef_key, chef) return Response({ 'success': True, 'url': chef.cover_thumb('library_edit_modal_cover') }) except Exception, e: return Response({ 'success': False, 'error': e }, status=status.HTTP_400_BAD_REQUEST)
def kitchen(request): recipe = Recipes.objects.create( chef=request.user, #name='Recipe, ' + datetime.datetime.now().strftime('%Y/%m/%d'), name='Unnamed Recipe', nb_shares=0, nb_likes=0, nb_comments=0, nb_added=0, creation_date=datetime.datetime.now(), edit_date=datetime.datetime.now(), commensals=0, private=0, ingredients_order='N;', draft=1, cache_score=0.0, cache_novelty_score=0.0, cache_likes=0, cache_likes_score=0, cache_photo_descriptions=0, cache_photo_descriptions_score=0.0, cache_added=0, cache_added_score=0, cache_photos=0, cache_photos_score=0.0, noted=0, manual_score=0.0, final_score=0.0, prep_time=0) #add_new_tag_to_recipe('#CHRISTMAS', recipe) #add_recipe_to_book(request, 'CHRISTMAS_BOOK', recipe) cache_utils = CacheUtils() cache_utils.reset_chef_cache(request.user.id) return HttpResponseRedirect( reverse('kitchen_draft', kwargs={'id': recipe.id}))
def get(self, request, *args, **kwargs): chef_id = request.user.id followings_json = [] cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_FOLLOWINGS, user_id=chef_id) followings_json = cache.get(key, None) if followings_json is None: chef = get_object_or_404(Chefs, pk=chef_id) followings_json = chef.json_follows_list cache.set(key, followings_json) return Response({ 'success': True, 'followings': followings_json }, status=status.HTTP_200_OK)
def get(self, request, *args, **kwargs): chef_id = request.user.id loves_json = [] cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.USER_LOVES, user_id=request.user.id) loves_json = cache.get(key, None) if loves_json is None: chef = get_object_or_404(Chefs, pk=chef_id) loves_json = chef.json_loves_list cache.set(key, loves_json) return Response({ 'success': True, 'loves': loves_json }, status=status.HTTP_200_OK)
def get(self, request, chef_id): try: chef_id = int(chef_id) except ValueError: return render(request, '410.html', status=410) cache = get_cache('default') list_followings_key = CacheUtils.get_key( CacheUtils.CHEF_FOLLOWINGS_LIST_10, chef_id=chef_id) list_followings = cache.get(list_followings_key, None) if list_followings is None: chef = get_object_or_404(Chefs, pk=chef_id) queryset = chef.following.all()[:10] serializer = LibraryChefSerializer(queryset, many=True) list_followings = serializer.data cache.set(list_followings_key, list_followings) return Response({'success': True, 'following': list_followings})
def post(self, request): try: book_name = request.POST.get('name') book_private = request.POST.get('private') == "1" book_collaborators = request.POST.get('collaborators', "") book_type = 'P' if book_private else 'N' if book_name == '': return Response({ 'success': False, }, status=status.HTTP_400_BAD_REQUEST) book = Book.objects.create(name=book_name, private=book_private, chef=request.user, book_type=book_type) book_application_service = BookApplicationService.new() book_application_service.set_book_collaborators( book, book_collaborators, request) book_serializer = WebBookSerializer(book) cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.CHEF_BOOKS, chef_id=request.user.id) cache.set(key, None) return Response({ 'success': True, 'book': book_serializer.data }, status=status.HTTP_200_OK) except Exception, e: print Exception, e traceback.print_exc() return Response( { 'success': False, 'message': 'Can not adding book' }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, recipe_id): try: file_obj = request.FILES['photo'] recipe = Recipes.objects.get(id=recipe_id) order = int(request.POST.get('order', 1)) if recipe.chef != request.user: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) photo = Photos.objects.create( recipe=recipe, creation_date=datetime.datetime.now(), edit_date=datetime.datetime.now(), photo_order=order, s3_url='') file_name = str(photo.id) + '.' + str( file_obj.name.split('.').pop()) path = default_storage.save(file_name, ContentFile(file_obj.read())) photo.s3_url = settings.MEDIA_URL + path photo.save() cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.RECIPE_STEPS, recipe_id=recipe_id) cache.set(key, None) serializer = KitchenPhotoSerializer(photo) return Response({ 'success': True, 'step_data': serializer.data }, status=status.HTTP_200_OK) except Exception, e: return Response({ 'success': False, 'error': e }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, book_id): try: book = Book.objects.get(pk=book_id) if book.chef != request.user: return Response({ 'success': False, }, status=status.HTTP_403_FORBIDDEN) book.delete() cache = get_cache('default') key = CacheUtils.get_key(CacheUtils.CHEF_BOOKS, chef_id=request.user.id) cache.set(key, None) return Response({'success': True}, status=status.HTTP_200_OK) except: return Response({ 'success': False, }, status=status.HTTP_400_BAD_REQUEST)
def draft(request, id): try: recipe_id = int(id) recipe = Recipes.objects.select_related('chef').get(id=recipe_id) if recipe.chef != request.user: return HttpResponseForbidden() #if recipe.draft == 0: # recipe.draft = 1 # recipe.save() cache_utils = CacheUtils() cache_utils.reset_chef_cache(request.user.id) books_serializer = KitchenBookSerializer(request.user.books.all(), many=True) books_json = json.dumps(books_serializer.data) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) cache = get_cache('default') keys = CacheUtils.refresh_recipe(CacheUtils(), recipe_id=recipe_id, chef_id=recipe.chef.id) for key in keys: cache.set(key, None) all_allergens = map(lambda a: a[1], settings.NC_ALLERGENS) response = dict(recipe=recipe, SITE=site, books=books_json, ALL_ALLERGENS=all_allergens) return render_to_response('kitchen/kitchen.html', response, context_instance=RequestContext(request)) except Recipes.DoesNotExist: raise Http404
def make_private(request, id): try: recipe_id = int(id) recipe = Recipes.objects.select_related('chef').get(id=recipe_id) if recipe.chef != request.user: return HttpResponseForbidden() recipe.draft = 0 recipe.private = 1 recipe.save() cache_utils = CacheUtils() cache_utils.reset_chef_cache(request.user.id) cache = get_cache('default') keys = CacheUtils.refresh_recipe(CacheUtils(), recipe_id=recipe_id, chef_id=recipe.chef.id) for key in keys: cache.set(key, None) if recipe.publication_date == None: # We will do it only the first time to track it at the analytics return HttpResponseRedirect( reverse('kitchen_congratulations', kwargs={'id': recipe.id})) else: site = RequestSite(request) response = dict(recipe=recipe, SITE=site) return render_to_response('kitchen/congratulations.html', response, context_instance=RequestContext(request)) except Recipes.DoesNotExist: raise Http404
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))
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))
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))
def book(request, id, need_login=False, need_change_password=False): try: book_id = int(id) except ValueError: raise Http404 need_login = False if request.session.has_key('need_login'): need_login = request.session['need_login'] if need_login == None: need_login = False request.session['need_login'] = None need_change_password = False if request.session.has_key('need_change_password'): need_change_password = request.session['need_change_password'] if need_change_password == None: need_change_password = False request.session['need_change_password'] = None buy_callback = False if request.session.has_key('buy_callback'): buy_callback = request.session['buy_callback'] if buy_callback == None: buy_callback = False request.session['buy_callback'] = None already_bought = False if request.session.has_key('already_bought'): already_bought = request.session['already_bought'] if already_bought == None: already_bought = False request.session['already_bought'] = None cache = get_cache('default') book_key = CacheUtils.get_key(CacheUtils.BOOK, book_id=book_id) book = cache.get(book_key, None) if settings.DEBUG or book is None: try: book = Book.objects.select_related('chef').get(id=book_id) cache.set(book_key, book) except Exception: raise Http404 if(book.chef != request.user): if (book.book_type != Book.TO_SELL and book.status != Book.AVAILABLE): raise PermissionDenied() book_cover_key = CacheUtils.get_key(CacheUtils.BOOK_COVER, book_id=book_id) book_cover = cache.get(book_cover_key, None) if settings.DEBUG or book_cover is None: if book.image: book_cover = book.image.url else: book_cover = thumbnail_url(book.cover, 'explore_cover') cache.set(book_cover_key, book_cover) book_recipes_key = CacheUtils.get_key(CacheUtils.BOOK_RECIPES, book_id=book_id) book_recipes = cache.get(book_recipes_key, None) if book_recipes is None: book_recipes = [] serializer = APIV1RecipesSerializer(book.recipes.all()) if request.user.is_authenticated(): serializer.user = request.user else: serializer.user = None book_recipes = json.dumps(serializer.data) cache.set(book_recipes_key, book_recipes) book_bought = ChefsHasBooks.objects.filter(chef__id=request.user.id, book__id=book.id).count() > 0 chef = book.chef 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() response = dict( book=book, book_price=book.price * 100 if book.price else 0, book_cover=book_cover, book_recipes=book_recipes, book_nb_recipes=book.recipes.count(), chef=chef, chef_avatar=chef_avatar, book_bought=book_bought, already_bought=already_bought, site=site, need_login=need_login, need_change_password=need_change_password, buy_callback=buy_callback, stripe_key=settings.STRIPE_KEY_PUBLIC ) return render_to_response('books/book.html', response, context_instance=RequestContext(request))