def refresh(self): """Retrieve the request session segments and verify whether or not they still apply to the requesting visitor. """ enabled_segments = Segment.objects.filter(status='enabled') persistent_segments = enabled_segments.filter(persistent=True) session_segments = self.request.session['segments'] rules = AbstractBaseRule.__subclasses__() # Create a list to store the new request session segments and # re-apply all persistent segments (if they are still enabled). new_segments = [segment for segment in session_segments if persistent_segments.filter(id=segment['id']).exists()] # Run tests on all remaining enabled segments to verify applicability. for segment in enabled_segments: segment_rules = [] for rule in rules: segment_rules += rule.objects.filter(segment=segment) result = self._test_rules(segment_rules, self.request, match_any=segment.match_any) if result: segdict = create_segment_dictionary(segment) if not any(seg['id'] == segdict['id'] for seg in new_segments): new_segments.append(segdict) self.request.session['segments'] = new_segments self.update_visit_count()
def set_segments(self, segments): """Set the currently active segments :param segments: The segments to set for the current request :type segments: list of wagtail_personalisation.models.Segment """ cache_segments = [] serialized_segments = [] segment_ids = set() for segment in segments: serialized = create_segment_dictionary(segment) if serialized['id'] in segment_ids: continue cache_segments.append(segment) serialized_segments.append(serialized) segment_ids.add(segment.pk) self.request.session['segments'] = serialized_segments self._segment_cache = cache_segments
def add(self, segment): """Add a segment to the request session. :param segment: The segment to add to the request session :type segment: wagtail_personalisation.models.Segment """ def check_if_segmented(item): """Check if the user has been segmented. :param item: The segment to check for :type item: wagtail_personalisation.models.Segment :returns: Whether the segment is in the request session :rtype: bool """ return any(seg['encoded_name'] == item.encoded_name() for seg in self.request.session['segments']) if not check_if_segmented(segment): segdict = create_segment_dictionary(segment) self.request.session['segments'].append(segdict)
def set_segments(self, segments, key="segments"): """Set the currently active segments :param segments: The segments to set for the current request :type segments: list of wagtail_personalisation.models.Segment :param key: The key under which to store the segments. Optional :type key: String """ cache_segments = [] serialized_segments = [] segment_ids = set() for segment in segments: serialized = create_segment_dictionary(segment) if serialized['id'] in segment_ids: continue cache_segments.append(segment) serialized_segments.append(serialized) segment_ids.add(segment.pk) self.request.session[key] = serialized_segments if key == "segments": self._segment_cache = cache_segments