/
base.py
2945 lines (2363 loc) · 95.9 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Base class for a resource in an API."""
from __future__ import annotations
import inspect
import logging
from typing import (Any, Callable, Dict, Final, List, Mapping, Optional,
Sequence, Set, TYPE_CHECKING, Tuple, Type, Union, cast)
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.fields.related_descriptors import (
ManyToManyDescriptor,
ForwardManyToOneDescriptor)
from django.db.models.query import QuerySet
from django.http.response import (HttpResponseNotAllowed,
HttpResponse,
HttpResponseBase,
HttpResponseNotModified)
from django.urls import include, path, re_path, reverse
from django.utils.functional import cached_property
from django.views.decorators.vary import vary_on_headers
from typing_extensions import (Literal, NotRequired, Protocol, TypeAlias,
TypedDict)
from djblets.auth.ratelimit import (RATE_LIMIT_API_ANONYMOUS,
RATE_LIMIT_API_AUTHENTICATED,
get_usage_count)
from djblets.util.http import (build_not_modified_from_response,
encode_etag,
etag_if_none_match,
get_http_requested_mimetype,
get_modified_since,
set_etag,
set_last_modified)
from djblets.webapi.auth.backends import check_login
from djblets.webapi.resources.registry import (get_resource_for_object,
_class_to_resources,
_name_to_resources)
from djblets.webapi.responses import (WebAPIResponse,
WebAPIResponseError,
WebAPIResponsePaginated)
from djblets.webapi.decorators import (SPECIAL_PARAMS,
webapi_login_required,
webapi_request_fields,
webapi_response_errors)
from djblets.webapi.errors import (DOES_NOT_EXIST,
LOGIN_FAILED,
NOT_LOGGED_IN,
PERMISSION_DENIED,
RATE_LIMIT_EXCEEDED,
WebAPIError)
from djblets.webapi.fields import IntFieldType
from djblets.webapi.responses import (WebAPIEventStream,
WebAPIResponseEventStream,
WebAPIResponseHeaders,
WebAPIResponsePayload)
if TYPE_CHECKING:
from datetime import datetime
from django.db.models import Model
from django.http import HttpRequest
from django.urls import URLPattern, URLResolver
from djblets.util.typing import KwargsDict
from djblets.webapi.fields import (BaseAPIFieldType,
ListFieldTypeItemsInfo)
from djblets.webapi.responses import (WebAPIResponseLink,
WebAPIResponseLinks)
class _SerializeLinkFunc(Protocol):
"""Internal type for a link serialization function.
Version Added:
4.0
"""
def __call__(
self,
obj: Any,
request: Optional[HttpRequest],
*args,
**kwargs,
) -> WebAPIResponseLink:
...
class _SerializeFieldFunc(Protocol):
"""Internal type for a field serialization function.
Version Added:
4.0
"""
def __call__(
self,
obj: Any,
request: Optional[HttpRequest],
**kwargs,
) -> WebAPIResponsePayload:
...
class _ExpandInfo(TypedDict):
"""Internal type for a dictionary covering expanded resource links.
Version Added:
4.0
"""
#: The mimetype of the expanded item resource.
#:
#: This is present whether using expanding list or item resources.
#:
#: Type:
#: str
item_mimetype: str
#: The mimetype of the expanded list resource, if any.
#:
#: Type:
#: str
list_mimetype: NotRequired[str]
#: The URL to an expanded list resource, if any.
#:
#: Type:
#: str
list_url: NotRequired[Optional[str]]
logger = logging.getLogger(__name__)
#: A utility type for API response payloads or event streams.
#:
#: Version Added:
#: 4.0
_PayloadOrEvents: TypeAlias = Union[
WebAPIResponsePayload,
WebAPIEventStream,
]
#: The result from an API method handler.
#:
#: API method handlers may return HTTP responses, API responses, API errors,
#: or tuples.
#:
#: Tuples may contain API errors or HTTP status codes, payloads or event
#: streams, and optional headers.
#:
#: Version Added:
#: 4.0
WebAPIResourceHandlerResult: TypeAlias = Union[
HttpResponseBase,
Tuple[WebAPIError, WebAPIResponsePayload, WebAPIResponseHeaders],
Tuple[WebAPIError, WebAPIResponsePayload],
Tuple[int, _PayloadOrEvents, WebAPIResponseHeaders],
Tuple[int, _PayloadOrEvents],
WebAPIError,
WebAPIResponse,
]
class WebAPIResourceFieldInfo(TypedDict):
"""Information on a field in a serialized API payload.
Version Added:
4.0
"""
#: A description of the field.
#:
#: This is in ReStructuredText format, and is intended for documentation
#: generation.
#:
#: Type
#: str
description: str
#: The type of field.
#:
#: This should be a :py:class:`~djblets.webapi.fields.BaseAPIFieldType`
#: subclass.
#:
#: For backwards-compatibiltiy, :py:class:`str`, :py:class:`bytes`,
#: :py:class:`bool`, :py:class:`int`, or a :py:class:`list, or
#: :py:class:`tuple` of string values can be specified, but these are
#: considered legacy.
type: Union[
Type[BaseAPIFieldType],
Type[bytes],
Type[str],
Type[bool],
Type[int],
Sequence[str],
]
#: The version of the product the field was added in.
#:
#: Type:
#: str
added_in: NotRequired[str]
#: A list of choices allowed for the field.
#:
#: This is available if using
# :py:class:`djblets.webapi.fields.ChoiceFieldType`.
choices: Sequence[str]
#: The version of the product the field was deprecated in.
#:
#: Type:
#: str
deprecated_in: NotRequired[str]
#: Information on the type in a list of items.
#:
#: This is available if using
# :py:class:`djblets.webapi.fields.ListFieldType`.
#:
#: Type:
#: dict
items: NotRequired[ListFieldTypeItemsInfo]
#: A referenced resource for the field.
#:
#: This is available if using
# :py:class:`djblets.webapi.fields.ResourceFieldType`.
#:
#: Type:
#: str or type
resource: NotRequired[Union[str, Type[WebAPIResource]]]
class AllowedMimetypeEntry(TypedDict):
"""An allowed mimetype for an item and list resource.
Version Added:
4.0
"""
#: An allowed mimetype for a list resource.
#:
#: This can be ``None`` or omitted in order to avoid defining a list
#: mimetype for this entry.
#:
#: Type:
#: str
item: NotRequired[Optional[str]]
#: An allowed mimetype for a list resource.
#:
#: This can be ``None`` or omitted in order to avoid defining an item
#: mimetype for this entry.
#:
#: Type:
#: str
list: NotRequired[Optional[str]]
class WebAPIResource(object):
"""A resource handling HTTP operations for part of the API.
A WebAPIResource is a RESTful resource living at a specific URL. It
can represent either an object or a list of objects, and can respond
to various HTTP methods (GET, POST, PUT, DELETE).
Subclasses are expected to override functions and variables in order to
provide specific functionality, such as modifying the resource or
creating a new resource.
For information on writing an API resource, see
:ref:`writing-api-resources`.
"""
#: A Django model backing this API resource.
#:
#: If provided, this resource will automatically handle querying and
#: representation of resource instances. Subclasses will still want to
#: handle access control, fields, parent resources, child resources, and
#: custom-build support for adding, updating, and deleting resources.
#:
#: Type:
#: type
model: Optional[Type[Model]] = None
#: A mapping of field names to definitions for any serialized objects.
#:
#: Each key should be a field name either present in :py:attr:`model` or
#: defined as a :samp:`serialize_<fieldname>_field` method.
#:
#: Type:
#: dict
fields: Mapping[
str,
Union[WebAPIResourceFieldInfo, Mapping[str, Any]]
] = {}
#: A regex for mapping keys for an object in an item resource.
#:
#: By default, this matches integers. Subclasses can override this to
#: match IDs with other values.
#:
#: Type:
#: str
uri_object_key_regex: str = r'[0-9]+'
#: The key to populate with the ID of an object in an item resource.
#:
#: Type:
#: str
uri_object_key: Optional[str] = None
#: The key on the provided model for matching an object key.
#:
#: This is used when :py:attr:`model` is set, allowing API resources to
#: automatically query for a model instance matching this model key to
#: the value in the URL corresponding to :py:attr:`uri_object_key`.
#:
#: Type:
#: str
model_object_key: str = 'pk'
#: A key on the provided model for matching a parent resource's model.
#:
#: This is used when :py:attr:`model` is set, allowing API resources to
#: locate the parent resource for the purposes of access checks and
#: URL generation.
#:
#: Type:
#: str
model_parent_key: Optional[str] = None
#: The field on an item resource object to use for a Last-Modified header.
#:
#: Type:
#: str
last_modified_field: Optional[str] = None
#: The field on an item resource object to use for an ETag header.
#:
#: Type:
#: str
etag_field: Optional[str] = None
#: Whether to auto-generate ETags for responses.
#:
#: If set, and an ETag is not otherwise provided, one will be generated
#: based on the response payload.
#:
#: Type:
#: bool
autogenerate_etags: bool = False
#: Whether the resource is a singleton.
#:
#: Singleton resources behave like an item resource without a parent list
#: resource. They have a single endpoint.
#:
#: Type:
#: bool
singleton: bool = False
#: A list of child resources to link to on the list resource.
#:
#: Type:
#: list of WebAPIResource
list_child_resources: Sequence[WebAPIResource] = []
#: A list of child resources to link to on the item resource.
#:
#: Type:
#: list of WebAPIResource
item_child_resources: Sequence[WebAPIResource] = []
#: A list of HTTP methods that are allowed on this resource.
#:
#: Subclasses must have resource handlers defined for each allowed HTTP
#: method.
#:
#: Type:
#: tuple of str
allowed_methods: Sequence[str] = ('GET',)
#: A vendor name to use within item and list resource mimetypes.
#:
#: This will be the ``vendor`` in
#: :samp:`{category}/vnd.{vendor}.{name}+{format}`.
#:
#: Type:
#: str
mimetype_vendor: Optional[str] = None
#: An explicit name to use within list resource mimetypees.
#:
#: This will be the ``name`` in
#: :samp:`{category}/vnd.{vendor}.{name}+{format}`.
#:
#: Type:
#: str
mimetype_list_resource_name: Optional[str] = None
#: An explicit name to use within item resource mimetypees.
#:
#: This will be the ``name`` in
#: :samp:`{category}/vnd.{vendor}.{name}+{format}`.
#:
#: Type:
#: str
mimetype_item_resource_name: Optional[str] = None
#: Mimetypes allowed for requests to the resource.
#:
#: Each entry defines optional item and/or list mimetypes that
#: correspond to :mailheader:`Accept` header values.
#:
#: Instances of this resource may have a modified version of the list
#: set on the class.
#:
#: Type:
#: list
allowed_mimetypes: Sequence[AllowedMimetypeEntry] = [
{
'list': mime,
'item': mime,
}
for mime in WebAPIResponse.supported_mimetypes
]
#: The class to use for paginated results in list resources.
#:
#: Type:
#: list
paginated_cls: Type[WebAPIResponsePaginated] = WebAPIResponsePaginated
#: A mapping of HTTP methods to handler method names.
#:
#: Type:
#: dict
method_mapping: Mapping[str, str] = {
'GET': 'get',
'POST': 'post',
'PUT': 'put',
'DELETE': 'delete',
}
#: A flag noting this class is an API handler.
#:
#: This is always ``True``. It's set to help middleware or other
#: processors differentiate API views from others.
#:
#: Type:
#: bool
is_webapi_handler: Final[bool] = True
######################
# Instance variables #
######################
#: The parent resource for this resource.
#:
#: Type:
#: WebAPIResource
_parent_resource: Optional[WebAPIResource] = None
#: A cached list of fields to pre-fetch when querying resources.
#:
#: This is automatically computed in :py:meth:`_get_queryset` once for
#: the lifetime of the resource instance.
#:
#: Type:
#: list of str
_prefetch_related_fields: List[str]
#: A cached list of fields to select when querying resources.
#:
#: This is automatically computed in :py:meth:`_get_queryset` once for
#: the lifetime of the resource instance.
#:
#: Type:
#: list of str
_select_related_fields: List[str]
def __init__(self) -> None:
"""Initialize the API resource.
This will register the resource and set up state required for
processing API requests.
"""
_name_to_resources[self.name] = self
_name_to_resources[self.name_plural] = self
_class_to_resources[self.__class__] = self
if self.mimetype_vendor:
# Generate list and item resource-specific mimetypes
# for each supported mimetype, and add them as a pair to the
# allowed mimetypes.
for mimetype_pair in self.allowed_mimetypes:
vend_mimetype_pair: AllowedMimetypeEntry = {
'list': None,
'item': None,
}
item_mimetype = mimetype_pair.get('item')
list_mimetype = mimetype_pair.get('list')
if (item_mimetype and
item_mimetype in WebAPIResponse.supported_mimetypes):
vend_mimetype_pair['item'] = self._build_resource_mimetype(
mimetype=item_mimetype,
is_list=False)
if (list_mimetype and
list_mimetype in WebAPIResponse.supported_mimetypes):
vend_mimetype_pair['list'] = self._build_resource_mimetype(
mimetype=list_mimetype,
is_list=True)
if vend_mimetype_pair['list'] or vend_mimetype_pair['item']:
self.allowed_mimetypes = list(self.allowed_mimetypes) + [
vend_mimetype_pair,
]
@vary_on_headers('Accept', 'Cookie')
def __call__(
self,
request: HttpRequest,
*args,
api_format: Optional[str] = None,
**kwargs,
) -> HttpResponseBase:
"""Invoke the correct HTTP handler based on the type of request.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
api_format (str, optional):
The API format requested by the caller (``json`` or ``xml``).
This is considered legacy and may be removed in a future
release.
*args (tuple):
Additional positional arguments passed by the URL dispatcher.
**kwargs (dict):
Keyword arguments representing values captured from the URL.
Returns:
django.http.HttpResponseBase:
The resulting HTTP response from the API handler.
"""
if not hasattr(request, '_djblets_webapi_object_cache'):
setattr(request, '_djblets_webapi_object_cache', {})
auth_result = check_login(request)
headers: WebAPIResponseHeaders = {}
if isinstance(auth_result, tuple):
auth_success, auth_message, auth_headers = auth_result
headers = auth_headers or {}
if not auth_success:
err = LOGIN_FAILED
if auth_message:
err = err.with_message(auth_message)
return WebAPIResponseError(
request,
err=err,
headers=headers,
api_format=api_format,
mimetype=self._build_error_mimetype(request))
# Check to see if the user has been rate limited. Rate limits for
# authentication failures have already been handled via the auth
# backend, so this just checks for the API rate limits, if any.
if auth_result:
rate_limit_type = RATE_LIMIT_API_AUTHENTICATED
else:
rate_limit_type = RATE_LIMIT_API_ANONYMOUS
usage = get_usage_count(request, increment=True,
limit_type=rate_limit_type)
if usage is not None and usage['count'] > usage['limit']:
headers['Retry-After'] = usage['time_left']
headers['X-RateLimit-Limit'] = usage['limit']
return WebAPIResponseError(
request,
err=RATE_LIMIT_EXCEEDED,
headers=headers,
api_format=api_format,
mimetype=self._build_error_mimetype(request))
method = request.method
if method == 'POST':
# Not all clients can do anything other than GET or POST.
# So, in the case of POST, we allow overriding the method
# used.
method = request.POST.get('_method', kwargs.get('_method', method))
elif method == 'PUT':
# Normalize the PUT data so we can get to it.
# This is due to Django's treatment of PUT vs. POST. They claim
# that PUT, unlike POST, is not necessarily represented as form
# data, so they do not parse it. However, that gives us no clean
# way of accessing the data. So we pretend it's POST for a second
# in order to parse.
#
# This must be done only for legitimate PUT requests, not faked
# ones using ?method=PUT.
try:
request.method = 'POST'
request._load_post_and_files()
request.method = 'PUT'
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
assert method is not None
setattr(request, '_djblets_webapi_method', method)
setattr(request, '_djblets_webapi_kwargs', kwargs)
setattr(request, 'PUT', request.POST)
view: Optional[Callable] = None
if method in self.allowed_methods:
if (method == 'GET' and
not self.singleton and
(self.uri_object_key is None or
self.uri_object_key not in kwargs)):
view = self.get_list
elif method:
method_name = self.method_mapping.get(method)
if method_name:
view = getattr(self, method_name, None)
response: HttpResponseBase
if view and callable(view):
assert not args
result = self.call_method_view(
request, method, view, api_format=api_format, *args, **kwargs)
if isinstance(result, WebAPIResponse):
response = result
elif isinstance(result, WebAPIError):
response = WebAPIResponseError(
request,
err=result,
api_format=api_format,
mimetype=self._build_error_mimetype(request))
elif isinstance(result, tuple):
if method == 'GET':
request_params = request.GET
else:
request_params = request.POST
if len(result) == 3:
# mypy doesn't type-narrow based on length, so we'll
# ignore the type error here.
headers.update(result[2]) # type: ignore
if 'Location' in headers:
extra_querystr = '&'.join(
'%s=%s' % (param, request_params[param])
for param in SPECIAL_PARAMS
if param in request_params
)
if extra_querystr:
if '?' in headers['Location']:
headers['Location'] += '&' + extra_querystr
else:
headers['Location'] += '?' + extra_querystr
result_code = result[0]
result_data = result[1]
if isinstance(result_code, WebAPIError):
response = WebAPIResponseError(
request,
err=result_code,
extra_params=cast(WebAPIResponsePayload, result_data),
api_format=api_format,
mimetype=self._build_error_mimetype(request))
else:
response_kwargs: KwargsDict = dict({
'api_format': api_format,
'encoder_kwargs': dict({
'calling_resource': self,
}, **kwargs),
}, **self.build_response_args(request))
headers.update(response_kwargs.pop('headers', {}))
if isinstance(result_data, (dict, list)):
# This is a standard response.
response = WebAPIResponse(
request,
status=result_code,
obj=cast(WebAPIResponsePayload, result_data),
**response_kwargs)
elif (inspect.isgeneratorfunction(result_data) or
inspect.isgenerator(result_data)):
# This is an event stream.
message_data_mimetype = \
response_kwargs.pop('mimetype')
response = WebAPIResponseEventStream(
result_data,
request=request,
status=result_code,
message_data_mimetype=message_data_mimetype,
**response_kwargs)
else:
# This is an unknown result.
raise AssertionError(
'Unsupported result from API handler: %r'
% result)
elif isinstance(result, HttpResponseBase):
response = result
else:
raise AssertionError(result)
if (isinstance(response, HttpResponse) and
200 <= response.status_code < 300):
# Check if there's no explicit ETag in a GET/HEAD request and
# the resource is told to generate missing ETags automatically.
#
# Starting in Djblets 2.0, we do this after a response payload
# is generated instead of up-front, so that we don't serialize
# the resource payload twice.
if (self.autogenerate_etags and
method in ('GET', 'HEAD') and
'ETag' not in response):
# There's no ETag, so we'll build one based on the payload
# content and check to see if the client already has it.
etag = encode_etag(response.content)
set_etag(response, etag)
if self.are_cache_headers_current(request, etag=etag):
response = build_not_modified_from_response(response)
else:
response = HttpResponseNotAllowed(self.allowed_methods)
# Make sure any headers we've collected along the way are in the
# response.
for header_name, header_value in headers.items():
response.setdefault(header_name, header_value)
return response
@property
def __name__(self):
"""Return the name of the API resource class.
Returns:
str:
The API resource class name.
"""
# Note that this catches the type for our __name__ property on the
# class, but in reality, accessing this on a class will get the
# actual class name. Ignore this here.
return self.__class__.__name__
@cached_property
def name(self) -> str:
"""The name of the resource, used for keys in the payloads.
If :py:attr:`model` is set, this will be the lowercase version of
the model name. Otherwise, it will be the lowercase version of this
resource class's name.
Subclasses can override this to set an explicit name.
Type:
str
"""
if self.model:
return self.model.__name__.lower()
else:
return self.__class__.__name__.lower() # type: ignore
return self._name
@cached_property
def name_plural(self) -> str:
"""The plural name of the object, used for lists.
If :py:attr:`singleton` is set, this will be the result of
:py:attr:`name`. Otherwise, it will be pluralized form of
:py:attr:`name`.
Subclasses can override this to set an explicit plural name.
Type:
str
"""
if self.singleton:
return self.name
else:
return f'{self.name}s'
@property
def item_result_key(self) -> str:
"""The key for serialized objects in an item payload.
This defaults to using :py:attr:`name` as the key. Subclasses can
override this to set an explicit key.
Type:
str
"""
return self.name
@property
def list_result_key(self) -> str:
"""The key for serialized object lists in a list payload.
This defaults to using :py:attr:`name_plural` as the key. Subclasses
can override this to set an explicit key.
Type:
str
"""
return self.name_plural
@cached_property
def uri_name(self) -> str:
"""The name of the resource in the URI.
This can be overridden when the name in the URI needs to differ
from the name used for the resource.
Type:
str
"""
return self.name_plural.replace('_', '-')
@property
def link_name(self) -> str:
"""The name of the resource for use in a link.
This can be overridden when the name in the link needs to differ
from the name used for the resource.
Type:
str
"""
return self.name_plural
@cached_property
def uri_template_name(self) -> Optional[str]:
"""The name of the resource for use in URI templates.
This will be used as the key for this resource in
:py:class:`djblets.webapi.resource.root.RootResource`'s list of URI
templates. This can be overridden when the URI template name for
this resource needs to differ from the name used for the resource.
This must be unique to the resource. If set to ``None`` this
resource will be excluded from the URI templates list.
Version Added:
3.1.0
Type:
str or None
"""
return self.name
@cached_property
def uri_template_name_plural(self) -> Optional[str]:
"""The plural name of the resource for use in URI templates.
This will be used as the key for the list version of this resource in
:py:class:`djblets.webapi.resource.root.RootResource`'s list of URI
templates. This can be overridden when the URI template name for
this resource needs to differ from the name used for the resource.
This must be unique to the resource. If set to ``None`` the list
version of this resource will be excluded from the URI templates list.
Version Added:
3.1.0
Type:
str or None
"""
uri_template_name = self.uri_template_name
if uri_template_name is None:
return None
elif uri_template_name == self.name:
return self.name_plural
elif self.singleton:
return self.uri_template_name
else:
return uri_template_name + 's'
def call_method_view(
self,
request: HttpRequest,
method: str,
view: Callable,
*args,
**kwargs,
) -> WebAPIResourceHandlerResult:
"""Call the given HTTP method handler view.
This will just call the given view by default, passing in all
args and kwargs.
This can be overridden by subclasses to perform additional
checks or pass additional data to the view.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
method (str):
The HTTP method used in the request.
view (callable):
The API handler function to call for the HTTP method.
*args (tuple):
Positional arguments to pass to the view.
**kwargs (dict):
Keyword arguments representing values captured from the URL.
"""
return view(request, *args, **kwargs)
def build_response_args(
self,
request: HttpRequest,
) -> KwargsDict:
"""Build keyword arguments to pass to a response class.
Args:
request (django.http.HttpRequest):
The HTTP request from the client.
Returns:
dict:
Keyword arguments to pass to the response class.
"""
is_list: bool = (
getattr(request, '_djblets_webapi_method', None) == 'GET' and
not self.singleton and
(self.uri_object_key is None or
self.uri_object_key not in getattr(request,
'_djblets_webapi_kwargs', []))
)
key: Literal['item', 'list']
if is_list:
key = 'list'
else:
key = 'item'
supported_mimetypes: Sequence[str] = [
mimetype
for mimetype in (
mime.get(key)
for mime in self.allowed_mimetypes
)
if mimetype
]
mimetype = get_http_requested_mimetype(request, supported_mimetypes)
if (mimetype and
self.mimetype_vendor and
mimetype in WebAPIResponse.supported_mimetypes):
mimetype = self._build_resource_mimetype(mimetype=mimetype,
is_list=is_list)
response_args: KwargsDict = {
'supported_mimetypes': supported_mimetypes,
'mimetype': mimetype,
}
if is_list:
for mimetype_pair in self.allowed_mimetypes:
if mimetype_pair.get('list') == mimetype:
item_mimetype = mimetype_pair.get('item')
if item_mimetype:
response_args['headers'] = {