def add_films_to_special_basket_by_film_id(self, user, film_id): rating_basket_key = self.cache_key(cache.CACHE_USER_BASKET, user) special_rating_basket_key = self.cache_key(cache.CACHE_SPECIAL_USER_BASKET, user) rating_basket = cache.get(rating_basket_key) or set() special_rating_basket = cache.get(special_rating_basket_key) or set() new_basket = [] related = self.get_related_film_ids(film_id) excluded = self.get_excluded_films() if related: new_basket = set(related) - excluded new_basket = set(list(new_basket)[:self.SPECIAL_BASKET_BONUS]) if new_basket: # how many we leave from the previous basket left_number = self.SPECIAL_RATE_BASKET_SIZE - len(new_basket) basket_list = list(special_rating_basket) # we throw old films to normal basket rating_basket.update(set(basket_list[left_number:])) # we leave some old ones in special basket new_basket.update(set(basket_list[:left_number])) cache.set(rating_basket_key, rating_basket, cache.A_MONTH) cache.set(special_rating_basket_key, new_basket, cache.A_MONTH)
def get_from_tag_basket(cls, user, tag, number_of_films=1): basket_key = cache.Key(cache.CACHE_TAG_BASKET, user, tag) no_films_key = cache.Key("no_films_left_for_tag", user, tag) # indicates whether there are any films left to show to user no_films = cache.get(no_films_key) if not no_films: tag_basket = cache.get(basket_key) or dict() if len(tag_basket) < number_of_films: cls.refill_tag_basket(user, tag) tag_basket = cache.get(basket_key) or dict() result = sorted(tag_basket, key=tag_basket.get, reverse=True)[:number_of_films] if not result: cache.set(no_films_key, True, cache.A_MONTH) else: for film_id in result: tag_basket.pop(film_id) cache.set(basket_key, tag_basket, cache.A_MONTH) defer(cls.refill_tag_basket, user, tag) return result else: return []
def get_films_to_rate(cls, user, number_of_films=1, tag=None): if not tag: rating_basket_key = cache.Key(cache.CACHE_USER_BASKET, user) special_rating_basket_key = cache.Key(cache.CACHE_SPECIAL_USER_BASKET, user) rating_basket = cache.get(rating_basket_key) or set() special_rating_basket = cache.get(special_rating_basket_key) or set() rating_basket.difference_update(special_rating_basket) if len(rating_basket) + len(special_rating_basket) < number_of_films: cls.refill_user_basket(user) rating_basket = cache.get(rating_basket_key) or set() rating_basket.difference_update(special_rating_basket) result = list(special_rating_basket) + list(rating_basket) result = result[:number_of_films] result_set = set(result) rating_basket.difference_update(result_set) special_rating_basket.difference_update(result_set) cache.set(rating_basket_key, rating_basket, cache.A_MONTH) cache.set(special_rating_basket_key, special_rating_basket, cache.A_MONTH) else: result = cls.get_from_tag_basket(user, tag, number_of_films=number_of_films) films = list(Film.objects.filter(id__in=result).select_related()) return films
def post(self, *args, **kw): key = cache.Key("questions_", self.request.unique_user) questions = cache.get(key) if "start" not in self.request.POST: self.check_answer(time.time()) if not questions: return self.on_end_questions() question = questions.pop() if question: cache.delete(key) # delete cache for questions cache.set(key, questions) # set cache for questions-1 key = cache.Key("answer_", self.request.unique_user) cache.set(key, question) # set cache for user answer context = self.get_context_data() context.update({ 'question': question or [], 'tstamp': time.time(), 'progress': (100-len(questions)*10), 'answered': 10-len(questions) }) return render(self.request, self.template_name, context )
def refill_tag_basket(cls, user, tag): TAG_BASKET_SIZE = getattr(settings, 'TAG_BASKET_SIZE') MIN_TAG_BASKET_SIZE = getattr(settings, 'MIN_TAG_BASKET_SIZE') try: lang = user.get_profile().LANG except AttributeError: lang = 'en' basket_key = cache.Key(cache.CACHE_TAG_BASKET, user, tag) tag_basket = cache.get(basket_key) or dict() if len(tag_basket) < MIN_TAG_BASKET_SIZE: # get films with this tag films_dict = Film.get_film_ids_by_tag(tag, lang) # get films seen by user seen_films = Film.get_user_seen_films(user) # remove films seen by user films_dict = dict([(k,v) for k,v in films_dict.items() if k not in seen_films]) # how many we want to refill to_refill = TAG_BASKET_SIZE - len(tag_basket) # reverse sort by popularity sorted_films = sorted(films_dict, key=films_dict.get, reverse=True)[:to_refill] refill_dict = dict([(fid, films_dict[fid]) for fid in sorted_films]) tag_basket.update(refill_dict) cache.set(basket_key, tag_basket, cache.A_MONTH)
def checked_in_users(self): key = cache.Key("festival_participants", self.object) users = cache.get(key) if users is None: from django.db.models import Min # fetch user checked-in on festival screenings users = list(User.objects.filter( screeningcheckin__screening__in=self.screening_set.get_screening_ids() ).annotate(Min('screeningcheckin__created_at'))) for u in users: u.activity_date = u.screeningcheckin__created_at__min users = dict( (u.id, u) for u in users ) # add users with activities tagged with festival tag users2 = User.objects.filter( user_activity__tagged_items__tag__name=self.object.tag.lower(), user_activity__LANG=settings.LANGUAGE_CODE, user_activity__created_at__gte=self.object.start_date, user_activity__created_at__lt=self.object.end_date + datetime.timedelta(days=1), profile__metacritic_name='', ).annotate(Min('user_activity__created_at')) for u in users2: u.activity_date = u.user_activity__created_at__min if not u.id in users or u.activity_date < users[u.id].activity_date: users[u.id] = u users = sorted(users.values(), key=lambda u:u.activity_date) cache.set(key, users) return users
def recompute_recommendations(user): engine.compute_user_features(user, save=True) key = cache_key("top_film_ids", MAX_RECOMMENDATIONS_NUMBER) film_ids = cache.get(key) if film_ids is None: film_ids = Film.objects.filter(popularity__gte=MIN_POPULARITY) film_ids = film_ids.with_poster().with_description().values_list( 'id', flat=True) film_ids = film_ids.exclude( production_country_list__icontains='Poland').exclude( production_country_list__icontains='Polska') film_ids = film_ids.order_by( '-popularity')[:MAX_RECOMMENDATIONS_NUMBER] film_ids = list(film_ids) cache.set(key, film_ids) recommendations = [ s for s in engine.compute_guess_score_for_films(user, film_ids).items() if s[1] ] recommendations = sorted(recommendations, key=lambda s: -s[1]) return recommendations
def delete_from_tag_basket(cls, user, id, tag): basket_key = cache.Key(cache.CACHE_TAG_BASKET, user, tag) tag_basket = cache.get(basket_key) or dict() if id in tag_basket: tag_basket.pop(id) cache.set(basket_key, tag_basket, cache.A_MONTH) defer(cls.refill_tag_basket, user, tag)
def regional_info(context): """ Display local info """ slug_city = None slug_region = None request = context['request'] user = request.user if user.is_authenticated(): profile = user.get_profile() try: slug_city = slughifi(profile.location) except AttributeError: slug_city = None if not slug_city: try: city = request.city except AttributeError: city = None slug_city = city and slughifi(city) or None key = cache.Key(CACHE_REGIONAL_INFO, slug_city) regional_info_obj = cache.get(key) if regional_info_obj is None and slug_city is not None: regional_info_obj = get_regional_info_obj(slug_city) cache.set(key, regional_info_obj) return {'regional_info': regional_info_obj,}
def get_screening_set(self, past=False): key = cache.Key("festival_screening_set", self, past) screening_set = cache.get(key) if screening_set is None: screening_set = FestivalScreeningSet(self, past=past) cache.set(key, screening_set) return screening_set
def get_country_and_tz_by_lat_lng(lat, lng): key = cache.Key('country_tz', lat, lng) data = cache.get(key) if data is None: data = _get_country_and_tz_by_lat_lng(lat, lng) cache.set(key, data) return data
def regional_info(context): """ Display local info """ slug_city = None slug_region = None request = context['request'] user = request.user if user.is_authenticated(): profile = user.get_profile() try: slug_city = slughifi(profile.location) except AttributeError: slug_city = None if not slug_city: try: city = request.city except AttributeError: city = None slug_city = city and slughifi(city) or None key = cache.Key(CACHE_REGIONAL_INFO, slug_city) regional_info_obj = cache.get(key) if regional_info_obj is None and slug_city is not None: regional_info_obj = get_regional_info_obj(slug_city) cache.set(key, regional_info_obj) return { 'regional_info': regional_info_obj, }
def latest_ratings(): """ Widget for main page (for unregistered users) displaying X random ratings by Filmaster users. """ key = cache.Key("latest_ratings") ratings = cache.get(key) NUMBER_OF_LATEST_RATINGS = getattr(settings, 'NUMBER_OF_LATEST_RATINGS', 10) NUMBER_OF_RATINGS_AT_MAIN_PAGE = getattr(settings, 'NUMBER_OF_RATINGS_AT_MAIN_PAGE', 4) if not ratings: ratings = UserActivity.objects.all_ratings().\ order_by('-created_at')[:NUMBER_OF_LATEST_RATINGS] cache.set(key, ratings, cache.A_DAY) try: ratings = random.sample(ratings, NUMBER_OF_RATINGS_AT_MAIN_PAGE) except ValueError: ratings = ratings[:NUMBER_OF_RATINGS_AT_MAIN_PAGE] return {'activities': ratings, }
def get_films_to_rate(self, number_of_films=1, tag=None): key = cache.Key("vue_rater_user_films", self.user) user_films = cache.get(key) if user_films is None: user_films = vue.get_ordered_known_film_ids() if self.SHUFFLE_BLOCK_SIZE: shuffled = [] while user_films: block = user_films[:self.SHUFFLE_BLOCK_SIZE] user_films = user_films[self.SHUFFLE_BLOCK_SIZE:] random.shuffle(block) shuffled.extend(block) user_films = shuffled cache.set(key, user_films) excluded = self.get_excluded_films() out = [] for film_id in user_films: if film_id not in excluded: out.append(film_id) if len(out) >= number_of_films: break out = [Film.get(id=id) for id in out] return out
def latest_checkins(): """ Widget for main page (for unregistered users) displaying X random check-ins by Filmaster users. """ key = cache.Key("latest-checkins") latest = cache.get(key) NUMBER_OF_LATEST_CHECKINS = getattr(settings, 'NUMBER_OF_LATEST_CHECKINS', 10) NUMBER_OF_CHECKINS_AT_MAIN_PAGE = getattr(settings, 'NUMBER_OF_CHECKINS_AT_MAIN_PAGE', 4) if not latest: now = datetime.now() ago = now - timedelta(hours=3) checkins = UserActivity.objects.all_checkins().order_by('-created_at') latest = list(checkins.filter(created_at__gte=ago)[:NUMBER_OF_LATEST_CHECKINS]) if len(latest) < NUMBER_OF_CHECKINS_AT_MAIN_PAGE: latest = list(checkins)[:NUMBER_OF_LATEST_CHECKINS] cache.set(key, latest, cache.CACHE_HOUR * 3) try: latest = random.sample(latest, NUMBER_OF_CHECKINS_AT_MAIN_PAGE) except ValueError: latest = latest[:NUMBER_OF_CHECKINS_AT_MAIN_PAGE] return {'activities': latest, }
def latest_checkins(): """ Widget for main page (for unregistered users) displaying X random check-ins by Filmaster users. """ key = cache.Key("latest-checkins") latest = cache.get(key) NUMBER_OF_LATEST_CHECKINS = getattr(settings, 'NUMBER_OF_LATEST_CHECKINS', 10) NUMBER_OF_CHECKINS_AT_MAIN_PAGE = getattr( settings, 'NUMBER_OF_CHECKINS_AT_MAIN_PAGE', 4) if not latest: now = datetime.now() ago = now - timedelta(hours=3) checkins = UserActivity.objects.all_checkins().order_by('-created_at') latest = list( checkins.filter(created_at__gte=ago)[:NUMBER_OF_LATEST_CHECKINS]) if len(latest) < NUMBER_OF_CHECKINS_AT_MAIN_PAGE: latest = list(checkins)[:NUMBER_OF_LATEST_CHECKINS] cache.set(key, latest, cache.CACHE_HOUR * 3) try: latest = random.sample(latest, NUMBER_OF_CHECKINS_AT_MAIN_PAGE) except ValueError: latest = latest[:NUMBER_OF_CHECKINS_AT_MAIN_PAGE] return { 'activities': latest, }
def latest_ratings(): """ Widget for main page (for unregistered users) displaying X random ratings by Filmaster users. """ key = cache.Key("latest_ratings") ratings = cache.get(key) NUMBER_OF_LATEST_RATINGS = getattr(settings, 'NUMBER_OF_LATEST_RATINGS', 10) NUMBER_OF_RATINGS_AT_MAIN_PAGE = getattr(settings, 'NUMBER_OF_RATINGS_AT_MAIN_PAGE', 4) if not ratings: ratings = UserActivity.objects.all_ratings().\ order_by('-created_at')[:NUMBER_OF_LATEST_RATINGS] cache.set(key, ratings, cache.A_DAY) try: ratings = random.sample(ratings, NUMBER_OF_RATINGS_AT_MAIN_PAGE) except ValueError: ratings = ratings[:NUMBER_OF_RATINGS_AT_MAIN_PAGE] return { 'activities': ratings, }
def count_guessed_rate(user, film): ratings = Rating.get_user_ratings(user) logger.info("counting guessed rate for film %d", film.id) if len(ratings) < MIN_USER_RATES: return None average_rate, average_weight = AVERAGE_RATE, AVERAGE_WEIGHT film_weight = 0.0 film_rate = film.average_score() or 0.0 film_rate = float(film_rate) if film_rate: film_weight = FILM_WEIGHT * pow( float(film.number_of_votes() / FILM_RELIABILITY_BAR), 0.3) user_rate = sum(ratings.values()) / len(ratings) user_weight = USER_WEIGHT * (len(ratings) / USER_RELIABILITY_BAR) ** 0.3 # film_ids = ratings.keys() # scores = dict(FilmComparator.objects.filter( # main_film=film, compared_film__id__in=film_ids).\ # values_list('compared_film', 'score')) key = cache.Key("compared_films", film.id) scores = cache.get(key) if scores is None: query = FilmComparator.objects.filter(main_film=film).values_list( 'compared_film', 'score') scores = dict((f, float(s)) for (f, s) in query) cache.set(key, scores) sum_weights = 0.0 sum_rate = 0.0 for film_id, rating in ratings.items(): if film_id in scores: weight = float(scores[film_id]) sum_weights += weight sum_rate += float(rating) * weight sum_rate += film_weight * film_rate + user_weight * user_rate sum_rate += average_weight * average_rate sum_weights += film_weight + user_weight + average_weight recommendation = None if sum_weights > 0.0 and sum_rate >= 0.0: score = Decimal(str(sum_rate / sum_weights)) if score <= 10: recommendation, created = Recommendation.objects.get_or_create( user=user, film=film, defaults=dict(guess_rating_alg2=score), ) if not created: recommendation.guess_rating_alg2 = score recommendation.save() # transaction.commit() return recommendation
def get_open_festivals(self): key = cache.Key("open_festivals") festivals = cache.get(key) if festivals is None: festivals = Festival.objects.filter(event_status=self.STATUS_OPEN) festivals = list(festivals) cache.set(key, festivals) return festivals
def get_fragments( self ): key = cache.Key( "fragments-set-%s" % self.key ) fragments = cache.get( key ) if fragments is None: fragments = Fragment.objects.filter( key=self.key ) cache.set( key, fragments, cache.A_MONTH ) return fragments
def __init__(self, queryset, page_size): self.queryset = queryset.order_by('id') key = cache.Key("sitemap_paginator", str(self.queryset.query)) self.ids = cache.get(key) if self.ids is None: self.ids = list(self.queryset.values_list('id', flat=True))[::page_size] cache.set(key, self.ids) self.num_pages = len(self.ids)
def get_fragments(self): key = cache.Key("fragments-set-%s" % self.key) fragments = cache.get(key) if fragments is None: fragments = Fragment.objects.filter(key=self.key) cache.set(key, fragments, cache.A_MONTH) return fragments
def get_open_festivals(self): key = cache.Key("open_festivals") festivals = cache.get(key) if festivals is None: festivals = Festival.objects.filter(event_status = self.STATUS_OPEN) festivals = list(festivals) cache.set(key, festivals) return festivals
def get_related_film_ids(self, film_id): key = self.cache_key("rater_related_films", film_id) related = cache.get(key) if related is None: film = Film.objects.get(id=film_id) related = list(film.get_related_films().values_list('id', flat=True)[:self.NUMBER_OF_FILMS_RELATED]) cache.set(key, related) return related
def delete_film_from_baskets_by_id(cls, user, film_id): # delete from tag baskets for tag in settings.BASKETS_TAGS_LIST: cls.delete_from_tag_basket(user, film_id, tag) # delete from regular basket rating_basket_key = cache.Key(cache.CACHE_USER_BASKET, user) rating_basket = cache.get(rating_basket_key) or set() rating_basket.discard(film_id) cache.set(rating_basket_key, rating_basket, cache.A_MONTH) # delete from special basket special_rating_basket_key = cache.Key(cache.CACHE_SPECIAL_USER_BASKET, user) special_rating_basket = cache.get(special_rating_basket_key) or set() special_rating_basket.discard(film_id) cache.set(special_rating_basket_key, special_rating_basket, cache.A_MONTH)
def get_films(self): key = cache.Key("festival_films", self) films = cache.get(key) if films is None: films = Film.objects.tagged(self.tag.lower()) films = list(films[:1000]) Film.update_ranking(films) cache.set(key, films) return films
def get_theaters(self): key = cache.Key("festival_theaters", self) theaters = cache.get(key) if theaters is None: from film20.tagging.models import TaggedItem channels = self.theaters.all() theaters = list(Channel.objects.theaters().filter(id__in=channels)) cache.set(key, theaters) return theaters
def get_unliked_film_ids(cls, user): if not user.id: return () key = cache.Key("unliked_recommendations", user.id) ret = cache.get(key) if ret is None: ret = cls.objects.filter(user=user, vote=0).values_list('film_id', flat=True) cache.set(key, ret) return ret
def get_user(self, user_id): key = cache.Key("user", user_id) user = settings.CACHED_USERS and cache.get(key) or None if not user: try: user = super(CachedModelBackend, self).get_user(user_id) cache.set(key, user) except User.DoesNotExist, e: pass
def matching_film_ids(self, include_ids, exclude_ids): key = cache.Key("features_film_ids", include_ids, exclude_ids) film_ids = cache.get(key) if film_ids is None: film_ids = Film.objects.filter(features__type__in=include_ids) if exclude_ids: film_ids = film_ids.exclude(features__type__in=exclude_ids) film_ids = set(film_ids.values_list('id', flat=True)) cache.set(key, film_ids) return film_ids
def get_user(self, user_id): key = cache.Key("user", user_id) user = settings.CACHED_USERS and cache.get(key) or None if not user: try: user = super(CachedModelBackend, self).get_user(user_id) if settings.CACHED_USERS: cache.set(key, user) except User.DoesNotExist, e: pass
def count_guessed_rate(user, film): ratings = Rating.get_user_ratings(user) logger.info("counting guessed rate for film %d", film.id) if len(ratings) < MIN_USER_RATES: return None average_rate, average_weight = AVERAGE_RATE, AVERAGE_WEIGHT film_weight = 0.0 film_rate = film.average_score() or 0.0 film_rate = float(film_rate) if film_rate: film_weight = FILM_WEIGHT * pow(float(film.number_of_votes() / FILM_RELIABILITY_BAR), 0.3) user_rate = sum(ratings.values()) / len(ratings) user_weight = USER_WEIGHT * (len(ratings) / USER_RELIABILITY_BAR) ** 0.3 # film_ids = ratings.keys() # scores = dict(FilmComparator.objects.filter( # main_film=film, compared_film__id__in=film_ids).\ # values_list('compared_film', 'score')) key = cache.Key("compared_films", film.id) scores = cache.get(key) if scores is None: query = FilmComparator.objects.filter(main_film=film).values_list("compared_film", "score") scores = dict((f, float(s)) for (f, s) in query) cache.set(key, scores) sum_weights = 0.0 sum_rate = 0.0 for film_id, rating in ratings.items(): if film_id in scores: weight = float(scores[film_id]) sum_weights += weight sum_rate += float(rating) * weight sum_rate += film_weight * film_rate + user_weight * user_rate sum_rate += average_weight * average_rate sum_weights += film_weight + user_weight + average_weight recommendation = None if sum_weights > 0.0 and sum_rate >= 0.0: score = Decimal(str(sum_rate / sum_weights)) if score <= 10: recommendation, created = Recommendation.objects.get_or_create( user=user, film=film, defaults=dict(guess_rating_alg2=score) ) if not created: recommendation.guess_rating_alg2 = score recommendation.save() # transaction.commit() return recommendation
def check_answer(self, serv_tstamp): question_key = cache.Key("answer_", self.request.unique_user) question = cache.get(question_key) if question: answer = question.get('answer', '') choice = int(self.request.POST.get('choice', 0)) user_tstamp = float(self.request.POST.get('tstamp')) if answer == choice: self.count_points(user_tstamp, serv_tstamp) cache.delete(question_key)
def get_vue_film_ids(skip_cache=False): key = cache_key("vue_film_ids") ids = cache.get(key) if not skip_cache and ids is not None: return ids ids = Film.objects.tagged('vue2012').values_list('id', flat=True) if len(ids) < 50: ids = Film.objects.all().order_by('-popularity').values_list('id', flat=True)[:150] ids = set(ids) cache.set(key, ids) return ids
def compute_guess_score_for_all_films(user): if not hasattr(user, '_guess_score'): key = cache.Key("guess_score", user.id) user._guess_score = cache.get(key) if user._guess_score is None: from film20.core.models import Recommendation items = Recommendation.objects.filter(user=user.id) items = items.values_list('film_id', 'guess_rating_alg2') user._guess_score = dict((r[0], float(r[1])) for r in items) cache.set(key, user._guess_score) return user._guess_score
def get_vue_film_ids(skip_cache=False): key = cache_key("vue_film_ids") ids = cache.get(key) if not skip_cache and ids is not None: return ids ids = Film.objects.tagged('vue2012').values_list('id', flat=True) if len(ids) < 50: ids = Film.objects.all().order_by('-popularity').values_list( 'id', flat=True)[:150] ids = set(ids) cache.set(key, ids) return ids
def to_recommend_ids(self, request): tag = request.GET.get('tag') key = cache.Key('saas_to_recommend_ids', tag) film_ids = cache.get(key) if film_ids is None: if tag: film_ids = Film.objects.tagged(tag) else: film_ids = Film.objects.filter(popularity__gt=20) film_ids = list(film_ids.values_list('id', flat=True)) cache.set(key, film_ids) return film_ids
def count_points(self, user_tstamp, serv_tstamp): quiz_points_key = cache.Key("points_", self.request.unique_user) quiz_points = cache.get(quiz_points_key) cache.delete(quiz_points_key) if not quiz_points: quiz_points = 0 tdelta = serv_tstamp - user_tstamp tdelta = int(round(tdelta)) quiz_points += settings.FBAPP.get('points').get('seconds').get(tdelta, 0) cache.set(quiz_points_key, quiz_points) return quiz_points
def add_points(self): quiz_points_key = cache.Key("points_", self.request.unique_user) quiz_points = cache.get(quiz_points_key) contest = self.get_contest() participant = ContestParticipation.objects.get(user=self.request.unique_user, contest=contest) if participant.state == ContestParticipation.STATE_TICKET: participant.quiz_count = quiz_points participant.score += quiz_points participant.state = ContestParticipation.STATE_QUIZ participant.save() cache.delete(quiz_points_key) return participant.score
def get(self, *args, **kw): context = self.get_context_data() contest = self.get_contest() participant = ContestParticipation.objects.get(user=self.request.unique_user, contest=contest) if participant.state >= ContestParticipation.STATE_QUIZ: return http.HttpResponseRedirect(self.get_next_step()) key = cache.Key("questions_", self.request.unique_user) questions = cache.get(key) if not questions: questions = self.quiz_mixer() cache.set(key, questions) return render(self.request, self.on_start, context)
def get_contest( self ): contest_key = cache.Key("contest") contest = cache.get(contest_key) if not contest: try: contest = Contest.objects.get(state=Contest.STATE_OPEN) except Contest.DoesNotExist: contest = Contest.objects.all().order_by('-final_date')[0] if contest.final_date < datetime.date.today(): contest.state = Contest.STATE_CLOSED contest.save() contest = Contest.objects.get(id=contest.id) cache.set(contest_key, contest) return contest
def get_screenings_for(self, date): key = cache.Key("festival_screenings", self, date) screenings = cache.get(key) if screenings is None: channels = self.theaters.all() films = Film.objects.tagged(self.tag.lower()) screenings = Screening.objects.filter( channel__in=channels, utc_time__gte=date, utc_time__lt=date + timedelta(days=1), film__film__in=films, ).order_by('utc_time') screenings = screenings.select_related('film', 'film__film', 'channel') screenings = list(screenings) cache.set(key, screenings) return screenings
def filmaster_recommends(): """ A widget displaying HTML from a selected flat page. Define this page in settings.py to FLATPAGE_FILMASTER_RECOMMENDS """ key = cache.Key(FLATPAGE_FILMASTER_RECOMMENDS) flat_page = cache.get(key) if flat_page is None: try: flat_page = FlatPage.objects.get(url=FLATPAGE_FILMASTER_RECOMMENDS) except FlatPage.DoesNotExist: flat_page = False cache.set(key, flat_page, cache.A_DAY) return {'flat_page': flat_page}
def main_page_activity_list(context): """ Widget for main page (for not logged in users) Displays list of recent activities on Filmaster. """ key = cache.Key("main_page_activities_displayed") displayed_activities = cache.get(key) if not displayed_activities: uahelper = UserActivityHelper() displayed_activities = uahelper.main_page_featured_activities() cache.set(key, displayed_activities, cache.CACHE_HOUR) return { 'activities': displayed_activities, 'request': context.get('request'), }
def invite_box(context): request = context['request'] assoc = None friends = [] if request.user.is_authenticated(): try: assoc = FBAssociation.objects.select_related('fb_user').get( user=request.user) if assoc.fb_user_id: key = cache.Key("some_fb_friends", assoc.fb_user_id) friends = cache.get(key) if friends is None: friends = assoc.fb_user.friends friends = list( friends.exclude( fbassociation__isnull=False).order_by('?')[0:100]) cache.set(key, friends) except FBAssociation.DoesNotExist, e: pass
def get_similar_films(skip_cache=False): """ returns dict(film_id, set(similar_films)) """ key = cache_key("similar_films") ret = cache.get(key) if not skip_cache and ret is not None: return ret q = SimilarFilm.objects.all() q = q.exclude(film_a__production_country_list__icontains='Poland').exclude( film_a__production_country_list__icontains='Polska') gr = itertools.groupby(q.order_by('film_b'), key=lambda s: s.film_b_id) d = dict((id, set(f.film_a_id for f in items)) for (id, items) in gr) cache.set(key, d) return d