def random_photos_for_species(species): key = 'species-photo-ids:%s' % species.pk photo_ids = r.smembers(key) if not photo_ids or len(photo_ids) < 2: photo_ids = list(species.visible_photos().values_list('pk',flat=True)) r.delete(key) for id in photo_ids: r.sadd(key, id) r.expire(key, 10 * 60) counts = [ c or 0 for c in r.mget( *['bestpics-photo-times-seen:%s' % i for i in photo_ids] ) ] # Pick first photo biased based on number of times they have been seen inverted_scores = [max(counts) - c for c in counts] first_photo = photo_ids[random_index_with_bias(inverted_scores)] remainder = list(id for id in photo_ids if id != first_photo) second_photo = random.choice(remainder) photos = list( Photo.objects.select_related('created_by').filter( pk__in = [first_photo, second_photo] ) ) random.shuffle(photos) return photos
def generate_token(): token = str(uuid.uuid1()) r.set(token, 1) r.expire(token, 6 * 60) return token