Skip to content

Commit 56cdd0d

Browse files
committed
Added visit page view
Fixes #74 Allows frontend users to submit page views and retrieve segments while behind a cache or CDN.
1 parent 4f9176d commit 56cdd0d

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

src/wagtail_personalisation/adapters.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def refresh(self):
169169

170170
self.update_visit_count()
171171

172-
def add_page_visit(self, page):
172+
def add_page_visit(self, page, path=None):
173173
visit_count = self.request.session.setdefault('visit_count', [])
174174
page_visits = [visit for visit in visit_count if visit['id'] == page.pk]
175175

@@ -181,6 +181,6 @@ def add_page_visit(self, page):
181181
visit_count.append({
182182
'slug': page.slug,
183183
'id': page.pk,
184-
'path': self.request.path,
184+
'path': path or self.request.path,
185185
'count': 1,
186186
})

src/wagtail_personalisation/views.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
from __future__ import absolute_import, unicode_literals
22

3-
from django.http import HttpResponseForbidden, HttpResponseRedirect
3+
from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponseBadRequest, JsonResponse
44
from django.shortcuts import get_object_or_404, reverse
5+
from django.views.decorators.cache import never_cache
6+
from django.views.decorators.http import require_POST
57
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
68
from wagtail.contrib.modeladmin.views import IndexView
79

@@ -88,3 +90,37 @@ def copy_page_view(request, page_id, segment_id):
8890
return HttpResponseRedirect(edit_url)
8991

9092
return HttpResponseForbidden()
93+
94+
95+
@never_cache
96+
@require_POST
97+
def visit_page(request):
98+
"""Allows a frontend user to submit a page view and retrieve their current
99+
segments on a site that is behind a cache or CDN.
100+
101+
On each page view, the user must POST to this view the page ID and path
102+
that they are browsing. It will return a JSON-formatted document containing
103+
a list of segments that are currently active for them.
104+
"""
105+
page_id = request.POST.get('page_id')
106+
path = request.POST.get('path')
107+
108+
if page_id is None or path is None:
109+
return HttpResponseBadRequest()
110+
111+
page = Page.objects.filter(id=page_id).only('id', 'slug', 'live').first()
112+
113+
if page is None or page.live is False:
114+
return HttpResponseBadRequest()
115+
116+
request.segment_adapter.add_page_visit(page, path=path)
117+
request.segments_adapter.refresh()
118+
119+
return JsonResponse {
120+
'segments': [
121+
{
122+
'slug': segment.encoded_name(),
123+
}
124+
for segment in request.segments_adapter.get_all_segments()
125+
]
126+
}

0 commit comments

Comments
 (0)