drf-rehive-extras 2.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ default_app_config = 'drf_rehive_extras.apps.DRFExtraConfig'
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DRFExtraConfig(AppConfig):
5
+ name = 'drf_rehive_extras'
6
+ verbose_name = "DRF Extra"
@@ -0,0 +1,92 @@
1
+ import re
2
+ from datetime import datetime
3
+ from functools import reduce
4
+
5
+ from django.utils.timezone import make_aware
6
+ from django.utils.translation import gettext_lazy as _
7
+ from rest_framework import serializers
8
+
9
+
10
+ class MetadataField(serializers.JSONField):
11
+ """
12
+ JSON field for metadata serialization.
13
+ """
14
+
15
+ def to_internal_value(self, data):
16
+ data = super().to_internal_value(data)
17
+
18
+ if data is None or not isinstance(data, dict):
19
+ raise serializers.ValidationError(
20
+ _('Invalid metadata. Must be a valid object.')
21
+ )
22
+
23
+ def _validate(obj):
24
+ if not isinstance(obj, dict):
25
+ return
26
+
27
+ for k, v in obj.items():
28
+ if (not re.match(r"^[a-zA-Z0-9\_]+$", k) or "__" in k):
29
+ raise serializers.ValidationError(
30
+ _("Invalid metadata key. May only contain alphanumeric"
31
+ " characters, numbers and single underscores.")
32
+ )
33
+ _validate(v)
34
+
35
+ _validate(data)
36
+
37
+ return data
38
+
39
+
40
+ class TimestampField(serializers.IntegerField):
41
+ """
42
+ Timestamp field for datetime serialization.
43
+ """
44
+
45
+ def __init__(self, *args, **kwargs):
46
+ self.multiplier = kwargs.pop('multiplier', 1000)
47
+ super().__init__(*args, **kwargs)
48
+
49
+ def to_representation(self, obj):
50
+ try:
51
+ return int(obj.timestamp() * self.multiplier)
52
+ except AttributeError:
53
+ return None
54
+
55
+ def to_internal_value(self, obj):
56
+ try:
57
+ date = int(obj) / int(self.multiplier)
58
+ except ValueError:
59
+ raise serializers.ValidationError(
60
+ _("Incorrect date format, must be a valid millisecond"
61
+ " timestamp.")
62
+ )
63
+
64
+ return make_aware(datetime.fromtimestamp(date))
65
+
66
+
67
+ class EnumField(serializers.ChoiceField):
68
+ """
69
+ Enum field for multiple choice enum values.
70
+ """
71
+
72
+ def __init__(self, enum, choices=None, **kwargs):
73
+ self.enum = enum
74
+ kwargs['choices'] = choices if choices else enum.choices()
75
+ super().__init__(**kwargs)
76
+
77
+ def to_representation(self, obj):
78
+ try:
79
+ return obj.value
80
+ except AttributeError:
81
+ return obj
82
+
83
+ def to_internal_value(self, data):
84
+ try:
85
+ # Check if the data is present inside self.choices
86
+ if not (any(
87
+ self.enum(key) == self.enum(data) for key
88
+ in self.choices.keys())):
89
+ raise ValueError
90
+ return self.enum(data)
91
+ except ValueError:
92
+ self.fail('invalid_choice', input=data)
@@ -0,0 +1,227 @@
1
+ from django.utils.translation import gettext_lazy as _
2
+ from rest_framework import status
3
+ from rest_framework.generics import GenericAPIView
4
+
5
+ from . import mixins
6
+
7
+
8
+ class BaseAPIView(GenericAPIView):
9
+ """
10
+ Generic view with extended features. All viewsets should extend this class.
11
+ """
12
+
13
+ # Modify the serializer classes used by the view based on the request
14
+ # method.
15
+ # This attribute can take two formats:
16
+ # - {"GET": ObjectSerializer}
17
+ # - {"GET": (RequestObjectSerializer, ResponseObjectSerializer,)}
18
+ serializer_classes = {}
19
+
20
+ # Modify the statuses used by the view based on the request method.
21
+ # This attributes can take the following format:
22
+ # - `{"GET": status.HTTP_200_OK}`
23
+ response_status_codes = {}
24
+
25
+ # The default statuses used by the view based on the request method.
26
+ default_response_status_codes = {
27
+ "GET": status.HTTP_200_OK,
28
+ "POST": status.HTTP_201_CREATED,
29
+ "PUT": status.HTTP_200_OK,
30
+ "PATCH": status.HTTP_200_OK,
31
+ # NOTE : We use 200 for deletes instead of 204 because the Rehive
32
+ # response format supports a `status` in the body and by default
33
+ # 204 expects there to be no response body.
34
+ "DELETE": status.HTTP_200_OK,
35
+ }
36
+
37
+ def get_serializer_class(self):
38
+ """
39
+ Retrieve the request serializer class for the view.
40
+
41
+ If the item returned from the serializer_classes is a tuple or list then
42
+ get the first class.
43
+ """
44
+
45
+ try:
46
+ c = self.serializer_classes[self.request.method]
47
+ except KeyError:
48
+ return super().get_serializer_class()
49
+
50
+ if isinstance(c, (tuple, list)) and len(c) >= 1:
51
+ return c[0]
52
+ else:
53
+ return c
54
+
55
+ def get_response_serializer_class(self):
56
+ """
57
+ Retrieve the response serializer class for the view.
58
+
59
+ If the item returned from the serializer_classes is a tuple or list then
60
+ get the second class if possible, otherwise get the first class.
61
+ """
62
+
63
+ try:
64
+ c = self.serializer_classes[self.request.method]
65
+ except KeyError:
66
+ return super().get_serializer_class()
67
+
68
+ if isinstance(c, (tuple, list)) and len(c) >= 1:
69
+ try:
70
+ return c[1]
71
+ except KeyError:
72
+ return c[0]
73
+ else:
74
+ return c
75
+
76
+ def get_response_serializer(self, *args, **kwargs):
77
+ """
78
+ Get the response serializer. Uses the custom
79
+ `get_response_serializer_class` instead of the default
80
+ `get_serializer_class`.
81
+ """
82
+
83
+ serializer_class = self.get_response_serializer_class()
84
+ kwargs.setdefault('context', self.get_serializer_context())
85
+ return serializer_class(*args, **kwargs)
86
+
87
+ def get_response_status_code(self):
88
+ """
89
+ Get the response status code.
90
+ """
91
+
92
+ try:
93
+ return self.response_status_codes[self.request.method]
94
+ except KeyError:
95
+ return self.default_response_status_codes[self.request.method]
96
+
97
+
98
+ class ActionAPIView(mixins.ActionMixin,
99
+ BaseAPIView):
100
+ """
101
+ Concrete view for performing a generic action.
102
+ """
103
+
104
+ response_status_codes = {
105
+ "POST": status.HTTP_200_OK
106
+ }
107
+
108
+ def post(self, request, *args, **kwargs):
109
+ return self.create(request, *args, **kwargs)
110
+
111
+
112
+ class CreateAPIView(mixins.CreateModelMixin,
113
+ BaseAPIView):
114
+ """
115
+ Concrete view for creating a model instance.
116
+ """
117
+
118
+ def post(self, request, *args, **kwargs):
119
+ return self.create(request, *args, **kwargs)
120
+
121
+
122
+ class ListAPIView(mixins.ListModelMixin,
123
+ BaseAPIView):
124
+ """
125
+ Concrete view for listing a queryset.
126
+ """
127
+
128
+ def get(self, request, *args, **kwargs):
129
+ return self.list(request, *args, **kwargs)
130
+
131
+
132
+ class RetrieveAPIView(mixins.RetrieveModelMixin,
133
+ BaseAPIView):
134
+ """
135
+ Concrete view for retrieving a model instance.
136
+ """
137
+
138
+ def get(self, request, *args, **kwargs):
139
+ return self.retrieve(request, *args, **kwargs)
140
+
141
+
142
+ class DestroyAPIView(mixins.DestroyModelMixin,
143
+ BaseAPIView):
144
+ """
145
+ Concrete view for deleting a model instance.
146
+ """
147
+
148
+ def delete(self, request, *args, **kwargs):
149
+ return self.destroy(request, *args, **kwargs)
150
+
151
+
152
+ class UpdateAPIView(mixins.UpdateModelMixin,
153
+ BaseAPIView):
154
+ """
155
+ Concrete view for updating a model instance.
156
+ """
157
+ def put(self, request, *args, **kwargs):
158
+ return self.update(request, *args, **kwargs)
159
+
160
+ def patch(self, request, *args, **kwargs):
161
+ return self.partial_update(request, *args, **kwargs)
162
+
163
+
164
+ class ListCreateAPIView(mixins.ListModelMixin,
165
+ mixins.CreateModelMixin,
166
+ BaseAPIView):
167
+ """
168
+ Concrete view for listing a queryset or creating a model instance.
169
+ """
170
+
171
+ def get(self, request, *args, **kwargs):
172
+ return self.list(request, *args, **kwargs)
173
+
174
+ def post(self, request, *args, **kwargs):
175
+ return self.create(request, *args, **kwargs)
176
+
177
+
178
+ class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
179
+ mixins.UpdateModelMixin,
180
+ BaseAPIView):
181
+ """
182
+ Concrete view for retrieving and updating a model instance.
183
+ """
184
+
185
+ def get(self, request, *args, **kwargs):
186
+ return self.retrieve(request, *args, **kwargs)
187
+
188
+ def put(self, request, *args, **kwargs):
189
+ return self.update(request, *args, **kwargs)
190
+
191
+ def patch(self, request, *args, **kwargs):
192
+ return self.partial_update(request, *args, **kwargs)
193
+
194
+
195
+ class RetrieveDestroyAPIView(mixins.RetrieveModelMixin,
196
+ mixins.DestroyModelMixin,
197
+ BaseAPIView):
198
+ """
199
+ Concrete view for retrieving and deleting a model instance.
200
+ """
201
+
202
+ def get(self, request, *args, **kwargs):
203
+ return self.retrieve(request, *args, **kwargs)
204
+
205
+ def delete(self, request, *args, **kwargs):
206
+ return self.destroy(request, *args, **kwargs)
207
+
208
+
209
+ class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
210
+ mixins.UpdateModelMixin,
211
+ mixins.DestroyModelMixin,
212
+ BaseAPIView):
213
+ """
214
+ Concrete view for retrieving, updating and deleting a model instance.
215
+ """
216
+
217
+ def get(self, request, *args, **kwargs):
218
+ return self.retrieve(request, *args, **kwargs)
219
+
220
+ def put(self, request, *args, **kwargs):
221
+ return self.update(request, *args, **kwargs)
222
+
223
+ def patch(self, request, *args, **kwargs):
224
+ return self.partial_update(request, *args, **kwargs)
225
+
226
+ def delete(self, request, *args, **kwargs):
227
+ return self.destroy(request, *args, **kwargs)
@@ -0,0 +1,249 @@
1
+ from rest_framework.response import Response
2
+ from rest_framework.settings import api_settings
3
+ from rest_framework.mixins import (
4
+ CreateModelMixin as DRFCreateModelMixin,
5
+ ListModelMixin as DRFListModelMixin,
6
+ RetrieveModelMixin as DRFRetrieveModelMixin,
7
+ UpdateModelMixin as DRFUpdateModelMixin,
8
+ DestroyModelMixin as DRFDestroyModelMixin
9
+ )
10
+ from django_filters.rest_framework import DjangoFilterBackend
11
+
12
+ from .pagination import PageNumberPagination, CursorPagination
13
+
14
+
15
+ def add_resource_data(request, instance):
16
+ """
17
+ Helper function to add resource infomation to the request. This info can
18
+ be used later on in the view context.
19
+
20
+ The resource data is populated with the single instance that is created,
21
+ updated or deleted (and does not include other resources modifed as a
22
+ result).
23
+
24
+ Resource data will only be populated if a RESOURCE and/or RESOURCE_ID is
25
+ available on the specific model instance.
26
+ """
27
+
28
+ # Attempt to a set a resource on the request.
29
+ try:
30
+ resource = getattr(instance, "RESOURCE")
31
+ except AttributeError:
32
+ return
33
+ else:
34
+ request._resource = resource
35
+
36
+ # Attempt to a set a resource ID on the request.
37
+ try:
38
+ field = getattr(instance, "RESOURCE_ID")
39
+ resource_id = getattr(instance, field)
40
+ except AttributeError:
41
+ return
42
+ else:
43
+ request._resource_id = str(resource_id)
44
+
45
+
46
+ class ActionMixin(DRFCreateModelMixin):
47
+ """
48
+ Perform a generic action.
49
+ """
50
+
51
+ def create(self, request, *args, **kwargs):
52
+ """
53
+ Handle object creation on the view.
54
+ """
55
+
56
+ # Handle the request serialization and creation.
57
+ serializer = self.get_serializer(data=request.data)
58
+ serializer.is_valid(raise_exception=True)
59
+ self.perform_create(serializer)
60
+
61
+ # Attach creation success headers.
62
+ headers = self.get_success_headers(serializer.data)
63
+
64
+ return Response(
65
+ data={'status': 'success'},
66
+ status=self.get_response_status_code(),
67
+ headers=headers
68
+ )
69
+
70
+
71
+ class CreateModelMixin(DRFCreateModelMixin):
72
+ """
73
+ Create a model instance.
74
+ """
75
+
76
+ def create(self, request, *args, **kwargs):
77
+ """
78
+ Handle object creation on the view.
79
+ """
80
+
81
+ # Handle the request serialization and creation.
82
+ serializer = self.get_serializer(data=request.data)
83
+ serializer.is_valid(raise_exception=True)
84
+ self.perform_create(serializer)
85
+
86
+ # Inject resource data into the request.
87
+ add_resource_data(request, serializer.instance)
88
+
89
+ # Attach creation success headers.
90
+ headers = self.get_success_headers(serializer.data)
91
+
92
+ # Handle the response serialization. Sometimes the serialization of
93
+ # responses should be different from the request serialization.
94
+ data = self.get_response_serializer(serializer.instance).data
95
+
96
+ return Response(
97
+ data={'status': 'success', 'data': data},
98
+ status=self.get_response_status_code(),
99
+ headers=headers
100
+ )
101
+
102
+
103
+ class ListModelMixin(DRFListModelMixin):
104
+ """
105
+ List a queryset.
106
+ """
107
+
108
+ filter_backends = (DjangoFilterBackend,)
109
+ pagination_class = PageNumberPagination
110
+
111
+ def get_pagination_class(self):
112
+ """
113
+ Get a paginator class based on a pagination field in a GET param.
114
+ """
115
+
116
+ paginator_name = self.request.GET.get('pagination')
117
+
118
+ try:
119
+ return {
120
+ "page": PageNumberPagination,
121
+ "cursor": CursorPagination
122
+ }[paginator_name]
123
+ except KeyError:
124
+ return self.pagination_class
125
+
126
+ @property
127
+ def paginator(self):
128
+ """
129
+ Fetch the correct paginator class.
130
+ """
131
+
132
+ if not hasattr(self, '_paginator'):
133
+ pagination_class = self.get_pagination_class()
134
+ if pagination_class is None:
135
+ self._paginator = None
136
+ else:
137
+ self._paginator = pagination_class()
138
+
139
+ return self._paginator
140
+
141
+ def list(self, request, *args, **kwargs):
142
+ """
143
+ Handle object listing on the view.
144
+ """
145
+
146
+ # Get a list of objects as a queryset.
147
+ queryset = self.filter_queryset(self.get_queryset())
148
+
149
+ # Paginate the queryset.
150
+ page = self.paginate_queryset(queryset)
151
+ if page is not None:
152
+ serializer = self.get_serializer(page, many=True)
153
+ return self.get_paginated_response(serializer.data)
154
+
155
+ # Handle serialization.
156
+ serializer = self.get_serializer(queryset, many=True)
157
+
158
+ return Response(
159
+ data={'status': 'success', 'data': serializer.data},
160
+ status=self.get_response_status_code()
161
+ )
162
+
163
+
164
+ class RetrieveModelMixin(DRFRetrieveModelMixin):
165
+ """
166
+ Retrieve a model instance.
167
+ """
168
+
169
+ def retrieve(self, request, *args, **kwargs):
170
+ """
171
+ Handle object retrieval on the view.
172
+ """
173
+
174
+ # Get a single object.
175
+ instance = self.get_object()
176
+
177
+ # Inject resource data into the request.
178
+ add_resource_data(request, instance)
179
+
180
+ # Handle serialization.
181
+ serializer = self.get_serializer(instance)
182
+
183
+ return Response(
184
+ data={'status': 'success', 'data': serializer.data},
185
+ status=self.get_response_status_code()
186
+ )
187
+
188
+
189
+ class UpdateModelMixin(DRFUpdateModelMixin):
190
+ """
191
+ Update a model instance.
192
+ """
193
+
194
+ def update(self, request, *args, **kwargs):
195
+ """
196
+ Handle object update on the view.
197
+ """
198
+
199
+ # Find out whether this is a partial (PATCH) or full (PUT) update.
200
+ partial = kwargs.pop('partial', False)
201
+
202
+ # Get a single object.
203
+ instance = self.get_object()
204
+
205
+ # Inject resource data into the request.
206
+ add_resource_data(request, instance)
207
+
208
+ # Handle serialization and update.
209
+ serializer = self.get_serializer(
210
+ instance, data=request.data, partial=partial
211
+ )
212
+ serializer.is_valid(raise_exception=True)
213
+ self.perform_update(serializer)
214
+
215
+ # Handle the response serialization. Sometimes the serialization of
216
+ # responses should be different from the request serialization.
217
+ data = self.get_response_serializer(serializer.instance).data
218
+
219
+ return Response(
220
+ data={'status': 'success', 'data': data},
221
+ status=self.get_response_status_code(),
222
+ )
223
+
224
+
225
+ class DestroyModelMixin(DRFDestroyModelMixin):
226
+ """
227
+ Destroy a model instance.
228
+ """
229
+
230
+ def destroy(self, request, *args, **kwargs):
231
+ """
232
+ Handle object destruction on the view.
233
+ """
234
+
235
+ # Get a single object.
236
+ instance = self.get_object()
237
+
238
+ # Inject resource data into the request.
239
+ add_resource_data(request, instance)
240
+
241
+ # Handle serialization and destroy.
242
+ serializer = self.get_serializer(instance, data=request.data)
243
+ self.perform_destroy(instance)
244
+
245
+ return Response(
246
+ data={'status': 'success'},
247
+ status=self.get_response_status_code()
248
+ )
249
+
@@ -0,0 +1,79 @@
1
+ from collections import OrderedDict
2
+
3
+ from rest_framework.pagination import (
4
+ PageNumberPagination as RestPageNumberPagination,
5
+ CursorPagination as RestCursorPagination
6
+ )
7
+ from rest_framework.response import Response
8
+
9
+
10
+ class PageNumberPagination(RestPageNumberPagination):
11
+ page_size = 15
12
+ page_size_query_param = 'page_size'
13
+ max_page_size = 250
14
+
15
+ def get_paginated_response(self, data):
16
+ response = OrderedDict([
17
+ ('count', self.page.paginator.count),
18
+ ('next', self.get_next_link()),
19
+ ('previous', self.get_previous_link()),
20
+ ('results', data)
21
+ ])
22
+
23
+ return Response(
24
+ OrderedDict([('status', 'success'), ('data', response)])
25
+ )
26
+
27
+
28
+ class CursorPagination(RestCursorPagination):
29
+ page_size = 15
30
+ page_size_query_param = 'page_size'
31
+ max_page_size = 250
32
+ # TODO, is there a reasonable way we can move orderby_query_param and
33
+ # orderby_fields into the filtersets, views or even models.
34
+ orderby_query_param = "orderby"
35
+ orderby_fields = ("created", "-created",)
36
+
37
+ def get_ordering(self, request, queryset, view):
38
+ """
39
+ Return a tuple of strings, that may be used in an `order_by` method.
40
+ """
41
+
42
+ # The default case is to check for an `ordering` attribute
43
+ # on this pagination instance.
44
+ ordering = self.ordering
45
+
46
+ # Check if the ordering is modified by a query param.
47
+ # Ensure that the ordering in the query param is an allowed field.
48
+ query_param_ordering = request.GET.get(self.orderby_query_param)
49
+ if query_param_ordering in self.orderby_fields:
50
+ ordering = request.GET[self.orderby_query_param]
51
+
52
+ assert ordering is not None, (
53
+ 'Using cursor pagination, but no ordering attribute was declared '
54
+ 'on the pagination class.'
55
+ )
56
+ assert '__' not in ordering, (
57
+ 'Cursor pagination does not support double underscore lookups '
58
+ 'for orderings. Orderings should be an unchanging, unique or '
59
+ 'nearly-unique field on the model, such as "-created" or "pk".'
60
+ )
61
+ assert isinstance(ordering, (str, list, tuple)), (
62
+ 'Invalid ordering. Expected string or tuple, but got {type}'.format(
63
+ type=type(ordering).__name__
64
+ )
65
+ )
66
+
67
+ if isinstance(ordering, str):
68
+ return (ordering,)
69
+
70
+ def get_paginated_response(self, data):
71
+ response = OrderedDict([
72
+ ('next', self.get_next_link()),
73
+ ('previous', self.get_previous_link()),
74
+ ('results', data)
75
+ ])
76
+
77
+ return Response(
78
+ OrderedDict([('status', 'success'), ('data', response)])
79
+ )