|
2 | 2 |
|
3 | 3 | from django import forms |
4 | 4 |
|
5 | | -from django.http import HttpResponseForbidden, HttpResponseRedirect |
| 5 | +from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponseBadRequest, JsonResponse |
6 | 6 | from django.shortcuts import get_object_or_404, reverse |
| 7 | +from django.views.decorators.cache import never_cache |
| 8 | +from django.views.decorators.http import require_POST |
7 | 9 | from django.utils.translation import ugettext_lazy as _ |
8 | 10 | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register |
9 | 11 | from wagtail.contrib.modeladmin.views import IndexView |
10 | 12 | from wagtail.wagtailcore.models import Page |
11 | 13 |
|
| 14 | +from wagtail_personalisation.adapters import get_segment_adapter |
12 | 15 | from wagtail_personalisation.models import Segment |
13 | 16 |
|
14 | 17 |
|
@@ -137,3 +140,36 @@ def copy_page_view(request, page_id, segment_id): |
137 | 140 | return HttpResponseRedirect(edit_url) |
138 | 141 |
|
139 | 142 | return HttpResponseForbidden() |
| 143 | + |
| 144 | + |
| 145 | +@never_cache |
| 146 | +@require_POST |
| 147 | +def visit_page(request): |
| 148 | + """Allows a frontend user to submit a page view and retrieve their current |
| 149 | + segments on a site that is behind a cache or CDN. |
| 150 | +
|
| 151 | + On each page view, the user must POST to this view the page ID and path |
| 152 | + that they are browsing. It will return a JSON-formatted document containing |
| 153 | + a list of segments that are currently active for them. |
| 154 | + """ |
| 155 | + segment_adapter = get_segment_adapter(request) |
| 156 | + page_id = request.POST.get('page_id') |
| 157 | + path = request.POST.get('path') |
| 158 | + |
| 159 | + if page_id is None or path is None: |
| 160 | + return HttpResponseBadRequest() |
| 161 | + |
| 162 | + page = Page.objects.filter(id=page_id).only('id', 'slug', 'live').first() |
| 163 | + |
| 164 | + if page is None or page.live is False: |
| 165 | + return HttpResponseBadRequest() |
| 166 | + |
| 167 | + segment_adapter.add_page_visit(page, path=path) |
| 168 | + segment_adapter.refresh() |
| 169 | + |
| 170 | + return JsonResponse({ |
| 171 | + 'segments': [ |
| 172 | + segment['encoded_name'] |
| 173 | + for segment in segment_adapter.get_segments() |
| 174 | + ] |
| 175 | + }) |
0 commit comments