djblets.webapi.resources.base¶
Base class for a resource in an API.
- WebAPIResourceHandlerResult¶
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.
New in version 4.0.
alias of
Union
[HttpResponseBase
,Tuple
[WebAPIError
,Dict
[Any
,Any
],Dict
[str
,str
]],Tuple
[WebAPIError
,Dict
[Any
,Any
]],Tuple
[int
,Union
[Dict
[Any
,Any
],Iterator
[WebAPIEventStreamMessage
],Callable
[[Optional
[str
]],Iterator
[WebAPIEventStreamMessage
]]],Dict
[str
,str
]],Tuple
[int
,Union
[Dict
[Any
,Any
],Iterator
[WebAPIEventStreamMessage
],Callable
[[Optional
[str
]],Iterator
[WebAPIEventStreamMessage
]]]],WebAPIError
,WebAPIResponse
]
- class WebAPIResourceFieldInfo[source]¶
Bases:
TypedDict
Information on a field in a serialized API payload.
New in version 4.0.
- description: str¶
A description of the field.
This is in ReStructuredText format, and is intended for documentation generation.
- Type
str
- type: Union[Type[BaseAPIFieldType], Type[bytes], Type[str], Type[bool], Type[int], Sequence[str]]¶
The type of field.
This should be a
BaseAPIFieldType
subclass.For backwards-compatibiltiy,
str
,bytes
,bool
,int
, or alist, or :py:class:`tuple
of string values can be specified, but these are considered legacy.
- resource: NotRequired[Union[str, Type[WebAPIResource]]]¶
Type: str or type
- __annotations__ = {'added_in': ForwardRef('NotRequired[str]', module='djblets.webapi.resources.base'), 'choices': ForwardRef('Sequence[str]', module='djblets.webapi.resources.base'), 'deprecated_in': ForwardRef('NotRequired[str]', module='djblets.webapi.resources.base'), 'description': ForwardRef('str', module='djblets.webapi.resources.base'), 'items': ForwardRef('NotRequired[ListFieldTypeItemsInfo]', module='djblets.webapi.resources.base'), 'resource': ForwardRef('NotRequired[Union[str, Type[WebAPIResource]]]', module='djblets.webapi.resources.base'), 'type': ForwardRef('Union[Type[BaseAPIFieldType], Type[bytes], Type[str], Type[bool], Type[int], Sequence[str]]', module='djblets.webapi.resources.base')}¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __required_keys__ = frozenset({'added_in', 'choices', 'deprecated_in', 'description', 'items', 'resource', 'type'})¶
- __total__ = True¶
- class AllowedMimetypeEntry[source]¶
Bases:
TypedDict
An allowed mimetype for an item and list resource.
New in version 4.0.
- item: Optional[str]¶
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:
- __annotations__ = {'item': ForwardRef('NotRequired[Optional[str]]', module='djblets.webapi.resources.base'), 'list': ForwardRef('NotRequired[Optional[str]]', module='djblets.webapi.resources.base')}¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __required_keys__ = frozenset({'item', 'list'})¶
- __total__ = True¶
- class WebAPIResource[source]¶
Bases:
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 Writing Web API Resources.
- model: Optional[Type[Model]] = None¶
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:
- fields: Mapping[str, Union[WebAPIResourceFieldInfo, Mapping[str, Any]]] = {}¶
A mapping of field names to definitions for any serialized objects.
Each key should be a field name either present in
model
or defined as aserialize_<fieldname>_field
method.- Type:
- uri_object_key_regex: str = '[0-9]+'¶
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:
- uri_object_key: Optional[str] = None¶
The key to populate with the ID of an object in an item resource.
- Type:
- model_object_key: str = 'pk'¶
The key on the provided model for matching an object key.
This is used when
model
is set, allowing API resources to automatically query for a model instance matching this model key to the value in the URL corresponding touri_object_key
.- Type:
- model_parent_key: Optional[str] = None¶
A key on the provided model for matching a parent resource’s model.
This is used when
model
is set, allowing API resources to locate the parent resource for the purposes of access checks and URL generation.- Type:
- last_modified_field: Optional[str] = None¶
The field on an item resource object to use for a Last-Modified header.
- Type:
- etag_field: Optional[str] = None¶
The field on an item resource object to use for an ETag header.
- Type:
- autogenerate_etags: bool = False¶
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:
- singleton: 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:
- list_child_resources: Sequence[WebAPIResource] = []¶
A list of child resources to link to on the list resource.
- Type:
- item_child_resources: Sequence[WebAPIResource] = []¶
A list of child resources to link to on the item resource.
- Type:
- allowed_methods: Sequence[str] = ('GET',)¶
A list of HTTP methods that are allowed on this resource.
Subclasses must have resource handlers defined for each allowed HTTP method.
- mimetype_vendor: Optional[str] = None¶
A vendor name to use within item and list resource mimetypes.
This will be the
vendor
incategory/vnd.vendor.name+format
.- Type:
- mimetype_list_resource_name: Optional[str] = None¶
An explicit name to use within list resource mimetypees.
This will be the
name
incategory/vnd.vendor.name+format
.- Type:
- mimetype_item_resource_name: Optional[str] = None¶
An explicit name to use within item resource mimetypees.
This will be the
name
incategory/vnd.vendor.name+format
.- Type:
- paginated_cls¶
The class to use for paginated results in list resources.
- Type:
alias of
WebAPIResponsePaginated
- method_mapping: Mapping[str, str] = {'DELETE': 'delete', 'GET': 'get', 'POST': 'post', 'PUT': 'put'}¶
A mapping of HTTP methods to handler method names.
- Type:
- is_webapi_handler: Final[bool] = True¶
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:
- __init__() None [source]¶
Initialize the API resource.
This will register the resource and set up state required for processing API requests.
- allowed_mimetypes: Sequence[AllowedMimetypeEntry] = [{'list': 'application/json', 'item': 'application/json'}, {'list': 'application/xml', 'item': 'application/xml'}]¶
Mimetypes allowed for requests to the resource.
Each entry defines optional item and/or list mimetypes that correspond to Accept header values.
Instances of this resource may have a modified version of the list set on the class.
- Type:
- __call__(request: HttpRequest, *args, api_format: Optional[str] = None, **kwargs) HttpResponseBase [source]¶
Invoke the correct HTTP handler based on the type of request.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.api_format (
str
, optional) –The API format requested by the caller (
json
orxml
).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:
The resulting HTTP response from the API handler.
- Return type:
django.http.HttpResponseBase
- name[source]¶
The name of the resource, used for keys in the payloads.
If
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:
- name_plural[source]¶
The plural name of the object, used for lists.
If
singleton
is set, this will be the result ofname
. Otherwise, it will be pluralized form ofname
.Subclasses can override this to set an explicit plural name.
- Type:
- property item_result_key: str[source]¶
The key for serialized objects in an item payload.
This defaults to using
name
as the key. Subclasses can override this to set an explicit key.- Type:
- property list_result_key: str[source]¶
The key for serialized object lists in a list payload.
This defaults to using
name_plural
as the key. Subclasses can override this to set an explicit key.- Type:
- uri_name[source]¶
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:
- property link_name: str[source]¶
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:
- uri_template_name[source]¶
The name of the resource for use in URI templates.
This will be used as the key for this resource in
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.New in version 3.1.0.
- uri_template_name_plural[source]¶
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
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.New in version 3.1.0.
- call_method_view(request: HttpRequest, method: str, view: Callable, *args, **kwargs) WebAPIResourceHandlerResult [source]¶
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.
- Parameters:
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.
- build_response_args(request: HttpRequest) KwargsDict [source]¶
Build keyword arguments to pass to a response class.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.- Returns:
Keyword arguments to pass to the response class.
- Return type:
- get_object(request: HttpRequest, id_field: Optional[str] = None, *args, **kwargs) Any [source]¶
Return an object, given the captured parameters from a URL.
This will perform a query for the object, taking into account
model_object_key
,uri_object_key
, and any captured parameters from the URL.This requires that
model
anduri_object_key`
are set.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.id_field (
str
, optional) –An explicit ID field on the object.
If not provided, this will default to
model_object_key
.*args (
tuple
) – Positional arguments passed to the API handler method.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Raises:
django.core.exceptions.ObjectDoesNotExist – The object does not exist in the database.
- post(request: HttpRequest, *args, api_format: Optional[str], **kwargs) WebAPIResourceHandlerResult [source]¶
Handle HTTP POST requests.
This is not meant to be overridden unless there are specific needs.
This will invoke
create()
if doing an HTTP POST on a list resource.By default, an HTTP POST is not allowed on individual object resources.
- Parameters:
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- put(request: HttpRequest, *args, api_format: Optional[str], **kwargs) WebAPIResourceHandlerResult [source]¶
Handle HTTP PUT requests.
This is not meant to be overridden unless there are specific needs.
This will invoke
update()
if doing an HTTP PUT.- Parameters:
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- get(**kwargs)[source]¶
Handle HTTP GETs to item resources.
By default, this will check for access permissions and query for the object. It will then return a serialized form of the object.
This may need to be overridden if needing more complex logic.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.api_format (
str
) – An explicit API format requested for the response.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- get_list(**kwargs)[source]¶
Handle HTTP GETs to list resources.
By default, this will query for a list of objects and return the list in a serialized form.
This may need to be overridden if needing more complex logic.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.api_format (
str
) – An explicit API format requested for the response.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- create(**kwargs)[source]¶
Handle HTTP POST requests to list resources.
This is used to create a new object on the list, given the data provided in the request. It should usually return HTTP 201 Created upon success.
By default, this returns HTTP 405 Method Not Allowed.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.api_format (
str
) – An explicit API format requested for the response.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- update(**kwargs)[source]¶
Handle HTTP PUT requests to object resources.
This is used to update an object, given full or partial data provided in the request. It should usually return HTTP 200 OK upon success.
By default, this returns HTTP 405 Method Not Allowed.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.api_format (
str
) – An explicit API format requested for the response.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- delete(**kwargs)[source]¶
Handles HTTP DELETE requests to object resources.
This is used to delete an object, if the user has permissions to do so.
By default, this deletes the object and returns HTTP 204 No Content.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.api_format (
str
) – An explicit API format requested for the response.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The HTTP response, API error, or tuple results from the API handler.
- Return type:
- get_queryset(request: Optional[HttpRequest], is_list: bool = False, *args, **kwargs) QuerySet [source]¶
Return a queryset used for querying objects or lists of objects.
Subclasses can override this to filter objects, include related objects, or otherwise specialize the queryset.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.is_list (
bool
, optional) –Whether this should be returning a queryset for a list resource.
Subclasses can use this to query additional state based on query arguments or other criteria.
*args (
tuple
) – Positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
A queryset for objects for this resource.
- Return type:
django.db.models.QuerySet
- Raises:
django.core.exceptions.ObjectDoesNotExist – The object does not exist. This may be thrown by an overridden function if the object or a parent object does not exist.
- get_url_patterns() List[Union[URLPattern, URLResolver]] [source]¶
Return the Django URL patterns for this object and its children.
This is used to automatically build up the URL hierarchy for all objects. Projects should call this for top-level resources and return them in the
urls.py
files.- Returns:
The list of URL patterns.
- Return type:
- has_access_permissions(request: HttpRequest, obj: Any, *args, **kwargs) bool [source]¶
Return whether the user has read access to the item resource.
This is used for HTTP GET requests on the item resource. For list resources, see
has_list_access_permissions()
.Subclasses should override this to provide any specific access control needed for accessing items.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
object
) – The object to check for permissions.*args (
tuple
) – Additional positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
True
if the user has access permissions.False
if it does not.- Return type:
- has_list_access_permissions(request: HttpRequest, *args, **kwargs) bool [source]¶
Return whether the user has read access to the list resource.
This is used for HTTP GET requests on the list resource. For item resources, see
has_access_permissions()
.By default, this will check the parent resource (if there is one) for access permissions.
Subclasses should override this to provide any specific access control needed for accessing lists of items.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Additional positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
True
if the user has access permissions.False
if it does not.- Return type:
- has_modify_permissions(request: HttpRequest, obj: Any, *args, **kwargs) bool [source]¶
Return whether the user can modify the object.
This is used for HTTP PUT requests on the item resource.
Subclasses should override this to provide any specific access control needed for modifying items.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
object
) – The object to check for permissions.*args (
tuple
) – Additional positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
True
if the user has modify permissions.False
if it does not.- Return type:
- has_delete_permissions(request: HttpRequest, obj: Any, *args, **kwargs) bool [source]¶
Return whether the user can delete this object.
This is used for HTTP DELETE requests on the list resource.
Subclasses should override this to provide any specific access control needed for deleting items.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
object
) – The object to check for permissions.*args (
tuple
) – Additional positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
True
if the user has delete permissions.False
if it does not.- Return type:
- get_link_serializer(field: str) _SerializeLinkFunc [source]¶
Return the function to use for serializing a link field.
This will first look for a function named
serialize_field_link
on the resource. If not available or not callable,serialize_link
will be returned.- Parameters:
field (
str
) – The field in the resource for which to generate a link.- Returns:
The link serializer function.
- Return type:
callable
- serialize_link(obj: Any, request: Optional[HttpRequest], *args, **kwargs) WebAPIResponseLink [source]¶
Return a serialized dictionary for a link.
This will find the resource serializer for a given object and return a dictionary containing information on the link.
- Parameters:
obj (
object
) – The object being linked to.request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The serialized link information.
- Return type:
- get_object_title(obj: Any, request: Optional[HttpRequest] = None, *args, **kwargs) str [source]¶
Return an object’s title.
This is called when generating a link to an object’s resource.
By default, this returns the object’s string representation. Subclasses can override this to return a different title.
- Parameters:
obj (
object
) – The object for which to generate a title.request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Additional positional arguments.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The object’s title.
- Return type:
- serialize_object(obj: Any, request: Optional[HttpRequest] = None, *args, **kwargs) WebAPIResponsePayload [source]¶
Return a serialized representation of an object.
This will generate a dictionary containing information on an object, based on the API resource serializer registered for the object type.
By default, the result will contain each field specified in
fields
, and any links to related resources in alinks
key.This also takes care of expanding any links into object payloads in the list of fields when passing a field name to
?expand=
(for HTTP GET) orexpand=
in the body (for POST or PUT).- Parameters:
obj (
object
) – The object to serialize.*args (
tuple
) – Positional arguments passed to the view.request (
django.http.HttpRequest
, optional) –The HTTP request from the client.
This can be
None
.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The serialized object payload.
- Return type:
- get_only_fields(request: Optional[HttpRequest]) Optional[List[str]] [source]¶
Return the list of the only fields that the payload should include.
If the user has requested that no fields should be provided, this will return an empty list.
If all fields will be included in the payload, this will return None.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.- Returns:
The list of fields, an empty list, or
None
.- Return type:
- get_only_links(request: Optional[HttpRequest]) Optional[List[str]] [source]¶
Return the list of the only links that the payload should include.
If the user has requested that no links should be provided, this will return an empty list.
If all links will be included in the payload, this will return None.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.- Returns:
The list of links, an empty list, or
None
.- Return type:
- get_serializer_for_object(obj: Any) Optional[WebAPIResource] [source]¶
Return the serializer used to serialize an object.
This is called when serializing objects for payloads returned by this resource instance. It must return the resource instance that will be responsible for serializing the given object for the payload.
By default, this calls
djblets.webapi.resources.registry. get_resource_for_object()
to find the appropriate resource.- Parameters:
obj (
object
) – The object to serialize.- Returns:
The resource handling serialization, or
None
if not found.- Return type:
- get_links(resources: Sequence[WebAPIResource] = [], obj: Optional[Any] = None, *args, request: Optional[HttpRequest] = None, **kwargs) WebAPIResponseLinks [source]¶
Return a dictionary of links coming off this resource.
The resulting links will point to the resources passed in
resources
, and will also provide special resources forself
(which points back to the official location for this resource) and one per HTTP method/operation allowed on this resource.- Parameters:
resources (
list
ofWebAPIResource
, optional) – A list of resources for which to generate additional links.obj (
object
, optional) – The object being serialized, for use as a base for resource URLs.*args (
tuple
) – Additional positional arguments passed to the view.request (
django.http.HttpRequest
) – The HTTP request from the client.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
A dictionary of link names to link information.
- Return type:
Return links related to this resource.
The result should be a dictionary of link names to a dictionary of information. See
djblets.webapi.responses.WebAPIResponseLink
for the available keys for each link.- Parameters:
obj (
object
, optional) – The object that the resources will be related to.request (
django.http.HttpRequest
, optional) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.**kwargs (
tuple
) – Keyword arguments representing values captured from the URL.
- Returns:
The dictionary of related links.
- Return type:
- get_href(obj: Any, request: Optional[HttpRequest], *args, **kwargs) Optional[str] [source]¶
Return the absolute URL for an object.
This will attempt to build a URL that points to the object’s item resource.
If
uri_object_key
is set, this will callget_item_url()
, passing the model’s key (defined asmodel_object_key
) asuri_object_key
, along with any parent IDs returned fromget_href_parent_ids()
.- Parameters:
obj (
object
) – The object being linked to.request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) – Positional arguments passed to the view.**kwargs (
dict
) –Keyword arguments representing values captured from the URL.
These will be passed to
get_href_parent_ids()
.
- Returns:
The resulting URL to the object, or
None
if it could not be generated.- Return type:
- get_list_url(**kwargs) str [source]¶
Return the absolute URL to the list version of this resource.
This will generate a URL for the list resource, given the provided arguments for the URL pattern.
By default, this calls
build_resource_url()
withname_plural
and the provided keyword arguments.- Parameters:
**kwargs (
dict
) –Keyword arguments representing values captured from the URL.
These will be passed to
build_resource_url()
.- Returns:
The resulting absolute URL to the list resource.
- Return type:
- get_item_url(**kwargs) str [source]¶
Return the absolute URL to the item version of this resource.
This will generate a URL for the item resource, given the provided arguments for the URL pattern.
By default, this calls
build_resource_url()
withname
and the provided keyword arguments.- Parameters:
**kwargs (
dict
) –Keyword arguments representing values captured from the URL.
These will be passed to
build_resource_url()
.- Returns:
The resulting absolute URL to the item resource.
- Return type:
- build_resource_url(name: str, request: Optional[HttpRequest] = None, **kwargs) str [source]¶
Build a resource URL for the given name and keyword arguments.
This can be overridden by subclasses that have special requirements for URL resolution.
- Parameters:
name (
str
) – The name of the resource.request (
django.http.HttpRequest
) – The HTTP request from the client.**kwargs (
dict
) –Keyword arguments representing values captured from the URL.
These will be passed to
_build_named_url()
.
- Returns:
The resulting absolute URL to the resource.
- Return type:
- get_href_parent_ids(obj: Any, **kwargs) Dict[str, str] [source]¶
Return a dictionary mapping parent object keys to object values.
This will walk up the resource tree and return a mapping of parent URI object keys to values in the object instances. These are meant to be used to generate a full URL back to this resource.
Each parent object’s resource class will be used to handle that level of the tree. The resource’s
model_parent_key
must be provided in order to process that level or higher in the tree.
- get_parent_object(obj: Any) Optional[Any] [source]¶
Return the parent of an object.
By default, this uses
model_parent_key
to figure out the parent.Subclasses can override this for more complex behavior.
- get_last_modified(request: HttpRequest, obj: Any) Optional[datetime] [source]¶
Return the last-modified timestamp of an object.
By default, this uses
last_modified_field
to determine what field in the model represents the last-modified timestamp of the object.Subclasses can override this for more complex behavior.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
object
) – The object for which to return a last-modified timestamp.
- Returns:
The last-modified timestamp, or
None
if not found.- Return type:
- get_etag(request: HttpRequest, obj: Any, *args, **kwargs) Optional[str] [source]¶
Return the ETag representing the state of the object.
By default, this uses
etag_field
to determine what field in the model is unique enough to represent the state of the object.Subclasses can override this for more complex behavior. Any overridden functions should make sure to pass the result through
encode_etag()
before returning a value.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
object
) – The object for which to return an ETag.*args (
tuple
) – Additional positional arguments passed to the view.**kwargs (
dict
) – Keyword arguments representing values captured from the URL.
- Returns:
The resulting encoded ETag, or
None
if one could not be generated.- Return type:
- encode_etag(request: HttpRequest, etag: str, *args, **kwargs) str [source]¶
Return an encoded ETag for usage in a header.
This will take a precomputed ETag, augment it with additional information, encode it as a SHA1, and return it.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.etag (
str
) – The ETag to encode.*args (
tuple
, unused) – Additional positional arguments passed to the view.**kwargs (
dict
, unused) – Keyword arguments representing values captured from the URL.
- Returns:
The encoded ETag.
- Return type:
- are_cache_headers_current(request: HttpRequest, last_modified: Optional[datetime] = None, etag: Optional[str] = None) bool [source]¶
Return whether cache headers from the client are current.
This will compare the optionally-provided timestamp and ETag against any conditional cache headers sent by the client to determine if the headers are current. If they are, the caller can return
HttpResponseNotModified
instead of a payload.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.last_modified (
datetime.datetime
, optional) – The current last-modified timestamp for the object, if available.etag (
str
, optional) – The current ETag for the payload, if available.
- Returns:
True
if the client’s cache headers represent a current version of the resource payload.False
if they do not.- Return type:
- get_no_access_error(request: HttpRequest, *args, **kwargs) WebAPIError [source]¶
Return an appropriate error when access is denied.
By default, this will return
PERMISSION_DENIED
if the user is logged in, andNOT_LOGGED_IN
if the user is anonymous.Subclasses can override this to return different or more detailed errors.
- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
, unused) – Additional positional arguments passed to the view.**kwargs (
dict
, unused) – Keyword arguments representing values captured from the URL.
- Returns:
The API error to send to the client.
- Return type:
- __annotations__ = {'_parent_resource': 'Optional[WebAPIResource]', '_prefetch_related_fields': 'List[str]', '_select_related_fields': 'List[str]', 'allowed_methods': 'Sequence[str]', 'allowed_mimetypes': 'Sequence[AllowedMimetypeEntry]', 'autogenerate_etags': 'bool', 'etag_field': 'Optional[str]', 'fields': 'Mapping[str, Union[WebAPIResourceFieldInfo, Mapping[str, Any]]]', 'is_webapi_handler': 'Final[bool]', 'item_child_resources': 'Sequence[WebAPIResource]', 'last_modified_field': 'Optional[str]', 'list_child_resources': 'Sequence[WebAPIResource]', 'method_mapping': 'Mapping[str, str]', 'mimetype_item_resource_name': 'Optional[str]', 'mimetype_list_resource_name': 'Optional[str]', 'mimetype_vendor': 'Optional[str]', 'model': 'Optional[Type[Model]]', 'model_object_key': 'str', 'model_parent_key': 'Optional[str]', 'paginated_cls': 'Type[WebAPIResponsePaginated]', 'singleton': 'bool', 'uri_object_key': 'Optional[str]', 'uri_object_key_regex': 'str'}¶