|
1 | 1 | from __future__ import absolute_import, unicode_literals |
2 | 2 |
|
3 | | -from django.http import HttpResponseForbidden, HttpResponseRedirect |
| 3 | +from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponseBadRequest, JsonResponse |
4 | 4 | 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 |
5 | 7 | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register |
6 | 8 | from wagtail.contrib.modeladmin.views import IndexView |
7 | 9 |
|
@@ -88,3 +90,37 @@ def copy_page_view(request, page_id, segment_id): |
88 | 90 | return HttpResponseRedirect(edit_url) |
89 | 91 |
|
90 | 92 | 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