Consumers

class AsyncAPIConsumer(*args, **kwargs)

This provides an async API consumer that is very inspired by DjangoRestFrameworks ViewSets.

permission_classes     An array for Permission classes
async add_group(name)

Add a group to the set of groups this consumer is subscribed to.

Parameters:

name (str) –

async check_permissions(action, **kwargs)

Check if the action should be permitted. Raises an appropriate exception if the request is not permitted.

Parameters:

action (str) –

async get_action_name(content, **kwargs)

Retrieves the action name from the json message.

Returns a tuple of the action name and the arguments that is passed to the action.

Override this method if you do not want to use {“action”: “action_name”} as the way to describe actions.

Parameters:

content (Dict) –

Return type:

Tuple[str | None, Dict]

async get_permissions(action, **kwargs)

Instantiates and returns the list of permissions that this view requires.

Parameters:

action (str) –

async handle_action(action, request_id, **kwargs)

Handle a call for a given action.

This method checks permissions and handles exceptions sending them back over the ws connection to the client.

If there is no action listed on the consumer for this action name a MethodNotAllowed error is sent back over the ws connection.

Parameters:
  • action (str) –

  • request_id (str) –

async handle_exception(exc, action, request_id)

Handle any exception that occurs, by sending an appropriate message

Parameters:
  • exc (Exception) –

  • action (str) –

async receive_json(content, **kwargs)

Called with decoded JSON content.

Parameters:

content (Dict) –

async remove_group(name)

Remove a group to the set of groups this consumer is subscribed to.

Parameters:

name (str) –

async reply(action, data=None, errors=None, status=200, request_id=None)

Send a json response back to the client.

You should aim to include the request_id if possible as this helps clients link messages they have sent to responses.

Parameters:

action (str) –

async websocket_connect(message)

Called when a WebSocket connection is opened.

async websocket_disconnect(message)

Called when a WebSocket connection is closed. Base level so you don’t need to call super() all the time.

@action(atomic=None, detached=None, **kwargs)[source]

Mark a method as an action.

Note

Should be used as a method decorator eg: @action()

It can be used on both async and sync methods.

from djangochannelsrestframework.decorators import action

class MyConsumer(AsyncAPIConsumer):

    @action()
    async def delete_user(self, request_id, user_pk, **kwargs):
        ...

Methods decorated with @action() will be called when a json message arrives from the client with a matching action name.

The default way of sending a message to call an action is:

{
 action: "delete_user",
 request_id: 42,
 user_pk: 82
}

You can alter how AsyncAPIConsumer matches the action using the get_action_name() method.


When using on async methods you can provide an additional option detached=True so that the method runs detached from the main run-loop of the consumer, allowing other actions on the consumer to be called while this action runs. This can be useful if the action needs to make further long-running async operations such as upstream network requests.

from djangochannelsrestframework.decorators import action

class MyConsumer(AsyncAPIConsumer):

    @action(detached=true)
    async def check_homepage(self, request_id, user_pk, **kwargs):
        async with aiohttp.ClientSession() as session:
            async with session.get('http://python.org') as response:
                return dict(response.headers), response.status

When using on sync methods you can provide an additional option atomic=True to forcefully wrap the method in a transaction. The default value for atomic is determined by django’s default db ATOMIC_REQUESTS setting.

Parameters:
  • atomic (bool | None) –

  • detached (bool | None) –

@detached[source]

Sets a method to run detached from the consumers main run-loop.

You should only do this for methods were you expect the runtime to be long (such as awaiting an upstream network request) and what to be able to handle other messages using the consumer while waiting.

If you need a detached action() then you should use @action(detached=True) instead.

Note

Should be used as a method decorator eg: @detached

This can only be applied to async methods:

from djangochannelsrestframework.decorators import detached

class MyConsumer(AsyncAPIConsumer):

    @detached
    async def on_message(self, *args, **kwargs):
        ...

Methods decorated with @detached are canceled when the websocket connection closes.

class GenericAsyncAPIConsumer(*args, **kwargs)[source]

Base class for all other generic views, this subclasses AsyncAPIConsumer.

queryset

will be accessed when the method get_queryset is called.

serializer_class

it should correspond with the queryset model, it will be used for the return response.

lookup_field

field used in the get_object method. Optional.

lookup_url_kwarg

url parameter used it for the lookup.

filter_queryset(queryset, **kwargs)[source]

Given a queryset, filter it with whichever filter backend is in use.

You are unlikely to want to override this method, although you may need to call it either from a list view, or from a custom get_object method if you want to apply the configured filtering backend to the default queryset.

Parameters:
  • queryset (QuerySet) – cached queryset to filter.

  • kwargs – keyworded dictionary arguments.

Returns:

Filtered queryset.

Return type:

QuerySet

Todos:

Implement

get_object(**kwargs)[source]

Returns the object the view is displaying.

You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.

Parameters:

kwargs – keyworded dictionary, it can be use it for filtering the queryset.

Returns:

Model object class.

Return type:

Model

Examples

>>> filtered_queryset = self.get_object(**{"field__gte": value})  # this way you could filter from the frontend.
get_queryset(**kwargs)[source]

Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using self.queryset.

This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.

You may want to override this if you need to provide different querysets depending on the incoming request.

(Eg. return a list of items that is specific to the user)

Parameters:

kwargs – keyworded dictionary.

Returns:

Queryset attribute.

Return type:

QuerySet

get_serializer(action_kwargs=None, *args, **kwargs)[source]

Return the serializer instance that should be used for validating and deserializing input, and for serializing output.

Parameters:
  • action_kwargs (Dict) – keyworded dictionary from the action.

  • args – listed arguments.

  • kwargs – keyworded dictionary arguments.

Returns:

Model serializer.

Return type:

Serializer

get_serializer_class(**kwargs)[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

Parameters:

kwargs – keyworded dictionary arguments.

Returns:

Model serializer class.

Return type:

Type[Serializer]

get_serializer_context(**kwargs)[source]

Extra context provided to the serializer class.

Parameters:

kwargs – keyworded dictionary arguments.

Returns:

Context dictionary, containing the scope and the consumer instance.

Return type:

Dict[str, Any]

view_as_consumer(wrapped_view, mapped_actions=None)

Wrap a django View to be used over a json ws connection.

websocket_urlpatterns = [
    re_path(r"^user/$", view_as_consumer(UserViewSet.as_view()))
]

This exposes the django view to your websocket connection so that you can send messages:

{
 action: "retrieve",
 request_id: 42,
 query: {pk: 92}
}

The default mapping for actions is:

  • create - PUT

  • update - PATCH

  • list - GET

  • retrieve - GET

Providing a query dict in the websocket messages results in the values of this dict being writen to the GET property of the request within your django view.

Providing a parameters dict within the websocket messages results in these values being passed as kwargs to the view method (in the same way that url parameters would normally be extracted).

Parameters:
  • wrapped_view (Callable[[HttpRequest], HttpResponse]) –

  • mapped_actions (Dict[str, str] | None) –

Return type:

DjangoViewAsConsumer