Guest User

Untitled

a guest
Jan 20th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.01 KB | None | 0 0
  1. import logging
  2. import os
  3.  
  4. from bakery.views import BuildableMixin
  5. from django.conf import settings
  6. from django.contrib.contenttypes.models import ContentType
  7. from wagtail.wagtailcore.models import Page, Site
  8. from wagtail.api.v2.endpoints import PagesAPIEndpoint
  9. from wagtail.api.v2.router import WagtailAPIRouter
  10. from wagtail.api.v2.pagination import WagtailPagination
  11.  
  12.  
  13. logger = logging.getLogger(__name__)
  14.  
  15.  
  16. class AllResultsWagtailPagination(WagtailPagination):
  17. """
  18. A pagination class that returns all results on a single page
  19. """
  20. def paginate_queryset(self, queryset, request, view=None):
  21. self.view = view
  22. self.total_count = queryset.count()
  23. return queryset
  24.  
  25.  
  26. class APIListingView(BuildableMixin):
  27. @property
  28. def build_method(self):
  29. return self.build_queryset
  30.  
  31. def get_build_path(self):
  32. target_path = os.path.join(settings.BUILD_DIR, self.build_path.lstrip('/'))
  33. if not self.fs.exists(os.path.dirname(target_path)):
  34. logger.debug("Creating {}".format(os.path.dirname(target_path)))
  35. self.fs.makedirs(os.path.dirname(target_path))
  36. return target_path
  37.  
  38. def build_queryset(self):
  39. logger.debug("Building %s" % self.build_path)
  40. self.request = self.create_request(self.build_path)
  41. target_path = os.path.join(settings.BUILD_DIR, self.get_build_path())
  42. self.build_file(target_path, self.get_content())
  43.  
  44.  
  45. class APIDetailView(BuildableMixin):
  46. """
  47. Render and build a "detail" view of an object.
  48.  
  49. Required attributes:
  50.  
  51. queryset:
  52. the model instance the objects are looked up from.
  53. """
  54. @property
  55. def build_method(self):
  56. return self.build_queryset
  57.  
  58. def get_url(self, obj):
  59. """
  60. The URL at which the detail page should appear.
  61. """
  62. if not hasattr(obj, 'get_absolute_url') or not obj.get_absolute_url():
  63. raise ImproperlyConfigured("No URL configured. You must either \
  64. set a ``get_absolute_url`` method on the %s model or override the %s view's \
  65. ``get_url`` method" % (obj.__class__.__name__, self.__class__.__name__))
  66. return obj.get_absolute_url()
  67.  
  68. def get_build_path(self, obj):
  69. """
  70. Used to determine where to build the detail page. Override this if you
  71. would like your detail page at a different location. By default it
  72. will be built at get_url()
  73. """
  74. target_path = os.path.join(settings.BUILD_DIR, self.get_url(obj).lstrip('/'))
  75. if not self.fs.exists(os.path.dirname(target_path)):
  76. logger.debug("Creating {}".format(os.path.dirname(target_path)))
  77. self.fs.makedirs(os.path.dirname(target_path))
  78. return target_path
  79.  
  80. def set_kwargs(self, obj):
  81. self.kwargs = {
  82. 'pk': getattr(obj, 'pk', None),
  83. }
  84.  
  85. def build_object(self, obj):
  86. logger.debug("Building %s" % obj)
  87. self.request = self.create_request(self.get_url(obj))
  88. self.set_kwargs(obj)
  89. target_path = self.get_build_path(obj)
  90. self.build_file(target_path, self.get_content())
  91.  
  92. def build_queryset(self):
  93. [self.build_object(o) for o in self.get_queryset().all()]
  94.  
  95. def unbuild_object(self, obj):
  96. """
  97. Deletes the file at self.get_build_path.
  98. """
  99. logger.debug("Unbuilding %s" % obj)
  100. target_path = os.path.split(self.get_build_path(obj))[0]
  101. if self.fs.exists(target_path):
  102. logger.debug("Removing {}".format(target_path))
  103. self.fs.removetree(target_path)
  104.  
  105. def get_content(self):
  106. # Create a dummy request
  107. request = self.create_request('/?format=json&fields=*')
  108. request.site = Site.objects.get(is_default_site=True)
  109. request.wagtailapi_router = WagtailAPIRouter('')
  110.  
  111. response = PagesAPIEndpointWithoutPagination.as_view({'get': 'detail_view'})(request, pk=self.kwargs['pk'])
  112. return response.render().content
  113.  
  114.  
  115. class PagesAPIEndpointWithoutPagination(PagesAPIEndpoint):
  116. pagination_class = AllResultsWagtailPagination
  117.  
  118.  
  119. class PagesAPIDetailView(APIDetailView):
  120. """
  121. Builds detail documents for every published page.
  122.  
  123. URL example: /api/pages/detail/1.json
  124. """
  125. endpoint_class = PagesAPIEndpointWithoutPagination
  126.  
  127. def get_url(self, page):
  128. return '/api/pages/detail/{}.json'.format(page.id)
  129.  
  130. def get_queryset(self):
  131. if getattr(settings, 'BAKERY_MULTISITE', False):
  132. return Page.objects.all().public().live()
  133. else:
  134. site = Site.objects.get(is_default_site=True)
  135. return site.root_page.get_descendants(inclusive=True).public().live()
  136.  
  137.  
  138. class PagesAPIListingView(APIListingView):
  139. """
  140. Builds a single listing that lists every published page.
  141.  
  142. URL example: /api/pages/all.json
  143. """
  144. build_path = '/api/pages/all.json'
  145.  
  146. def get_url(self):
  147. return self.build_path
  148.  
  149. def fetch_page_listing(self, page_model=None):
  150. if page_model:
  151. url = '/?format=json&fields=*&type={}.{}'.format(page_model._meta.app_label, page_model.__name__)
  152. else:
  153. url = '/?format=json&fields=*'
  154.  
  155. request = self.create_request(url)
  156. request.site = Site.objects.get(is_default_site=True)
  157. request.wagtailapi_router = WagtailAPIRouter('')
  158. response = PagesAPIEndpointWithoutPagination.as_view({'get': 'listing_view'})(request)
  159. return response.render().content
  160.  
  161. def get_content(self):
  162. return self.fetch_page_listing()
  163.  
  164.  
  165. class TypedPagesAPIListingView(PagesAPIListingView):
  166. """
  167. Builds a listing for each page type. Containing all published
  168. pages of that type.
  169.  
  170. URL example: /api/pages/blog_BlogPage.json
  171. """
  172. build_path = '/api/pages/{app_label}_{class_name}.json'
  173.  
  174. def get_url(self, cls):
  175. return self.build_path.format(
  176. app_label=cls._meta.app_label,
  177. class_name=cls.__name__,
  178. )
  179.  
  180. def get_content(self):
  181. return self.fetch_page_listing(self.kwargs['cls'])
  182.  
  183. def set_kwargs(self, cls):
  184. self.kwargs = {
  185. 'cls': cls,
  186. }
  187.  
  188. def get_build_path(self, cls):
  189. target_path = os.path.join(settings.BUILD_DIR, self.get_url(cls).lstrip('/'))
  190. if not self.fs.exists(os.path.dirname(target_path)):
  191. logger.debug("Creating {}".format(os.path.dirname(target_path)))
  192. self.fs.makedirs(os.path.dirname(target_path))
  193. return target_path
  194.  
  195. def build_page_type(self, cls):
  196. logger.debug("Building %s" % cls)
  197. self.request = self.create_request(self.get_url(cls))
  198. self.set_kwargs(cls)
  199. target_path = self.get_build_path(cls)
  200. self.build_file(target_path, self.get_content())
  201.  
  202. def get_page_types(self):
  203. return [
  204. content_type.model_class()
  205. for content_type in ContentType.objects.filter(id__in=Page.objects.values_list('content_type_id', flat=True))
  206. ]
  207.  
  208. def build(self):
  209. for page_type in self.get_page_types():
  210. self.build_page_type(page_type)
  211.  
  212. @property
  213. def build_method(self):
  214. return self.build
Add Comment
Please, Sign In to add comment