Channels
Strawberry provides support for Channels with Consumers to provide GraphQL support over WebSockets and HTTP.
Introduction
While Channels does require Django to be installed as a dependency, you can actually run this integration without using Django’s request handler. However, the most common use case will be to run a normal Django project with GraphQL subscriptions support, typically taking advantage of the Channel Layers functionality which is exposed through the Strawberry integration.
Getting Started
Pre-requisites
Make sure you have read the following Channels documentation:
- Introduction
- Tutorial
- Consumers
- And our Subscriptions documentation.
If you have read the Channels documentation, You should know by now that:
- ASGI application is a callable that can handle multiple send / receive operations without the need of a new application instance.
- Channels is all about making ASGI applications instances (whether in another processes or in another machine) talk to each other seamlessly.
- A
scope
is a single connection represented by a dict, whether it would be a websocket or an HTTP request or another protocol. - A
Consumer
is an ASGI application abstraction that helps to handle a single scope.
Installation
Before using Strawberry’s Channels support, make sure you install all the required dependencies by running:
Tutorial
The following example will pick up where the Channels tutorials left off.
By the end of this tutorial, You will have a graphql chat subscription that will be able to talk with the channels chat consumer from the tutorial.
Types setup
First, let's create some Strawberry-types for the chat.
Channel Layers
The Context for Channels integration includes the consumer, which has an instance of the channel layer and the consumer's channel name. This tutorial is an example of how this can be used in the schema to provide subscriptions to events generated by background tasks or the web server. Even if these are executed in other threads, processes, or even other servers, if you are using a Layer backend like Redis or RabbitMQ you should receive the events.
To set this up, you'll need to make sure Channel Layers is configured as per the documentation .
Then you'll want to add a subscription that accesses the channel layer and joins one or more broadcast groups.
Since listening for events and passing them along to the client is a common use case, the base consumer provides a high level API for that using a generator pattern, as we will see below.
The chat subscription
Now we will create the chat subscription .
Explanation: Info.context["ws"]
or Info.context["request"]
is a pointer to
the ChannelsConsumer
instance. Here we have first sent a
message to all the channel_layer groups (specified in the subscription argument
rooms
) that we have joined the chat.
The ChannelsConsumer
instance is shared between all subscriptions created in a
single websocket connection. The ws.listen_to_channel
context manager will
return a function to yield all messages sent using the given message type
(chat.message
in the above example) but does not ensure that the message was
sent to the same group or groups that it was called with - if another
subscription using the same ChannelsConsumer
also uses ws.listen_to_channel
with some other group names, those will be returned as well.
In the example we ensure message["room_id"] in room_ids
before passing
messages on to the subscription client to ensure subscriptions only receive
messages for the chat rooms requested in that subscription.
We do not need to call await channel_layer.group_add(room, ws.channel_name)
if
we don’t want to send an initial message while instantiating the subscription.
It is handled by ws.listen_to_channel
.
Chat message mutation
If you noticed, the subscription client can’t send a message willingly. You will
have to create a mutation for sending messages via the channel_layer
Creating the consumers
All we did so far is useless without creating an asgi consumer for our schema.
The easiest way to do that is to use the
GraphQLProtocolTypeRouter
which will wrap your
Django application, and route HTTP and websockets for "/graphql"
to
Strawberry, while sending all other requests to Django. You’ll need to modify
the myproject.asgi.py
file from the Channels instructions to look something
like this:
This approach is not very flexible, taking away some useful capabilities of
Channels. For more complex deployments, i.e you want to integrate several ASGI
applications on different URLs and protocols, like what is described in the
Channels documentation .
You will probably craft your own
ProtocolTypeRouter
.
An example of this (continuing from channels tutorial) would be:
This example demonstrates some ways that Channels can be set up to handle
routing. A very common scenario will be that you want user and session
information inside the GraphQL context, which the AuthMiddlewareStack wrapper
above will provide. It might be apparent by now, there's no reason at all why
you couldn't run a Channels server without any Django ASGI application at all.
However, take care to ensure you run django.setup()
instead of
get_asgi_application()
, if you need any Django ORM or other Django features in
Strawberry.
Running our example
First run your asgi application (The ProtocolTypeRouter) using your asgi server. If you are coming from the channels tutorial, there is no difference. Then open three different tabs on your browser and go to the following URLs:
-
localhost:8000/graphql
-
localhost:8000/graphql
-
localhost:8000/chat
If you want, you can run 3 different instances of your application with different ports it should work the same!
On tab #1 start the subscription:
On tab #2 we will run sendChatMessage
mutation:
On tab #3 we will join the room you subscribed to ("room1") and start chatting.
Before we do that there is a slight change we need to make in the ChatConsumer
you created with channels in order to make it compatible with our
ChatRoomMessage
type.
Look here for some more complete examples:
- The Strawberry Examples repo contains a basic example app demonstrating subscriptions with Channels.
Confirming GraphQL Subscriptions
By default no confirmation message is sent to the GraphQL client once the subscription has started. However, this is useful to be able to synchronize actions and detect communication errors. The code below shows how the above example can be adapted to send a null from the server to the client to confirm that the subscription has successfully started. This includes confirming that the Channels layer subscription has started.
Note the change in return signature for join_chat_rooms
and the yield None
after entering the listen_to_channel
context manger.
Testing
We provide a minimal application communicator (GraphQLWebsocketCommunicator
)
for subscribing. Here is an example based on the tutorial above: Make sure you
have pytest-async installed
In order to test a real server connection we can use python
gql client and channels
ChannelsLiveServerTestCase
.
This example is based on the extended ChannelsLiveServerTestCase
class from
channels tutorial part 4. You cannot run this test with a pytest session.
Add this test in your ChannelsLiveServerTestCase
extended class:
The HTTP and WebSockets protocol are handled by different base classes. HTTP
uses GraphQLHTTPConsumer
and WebSockets uses GraphQLWSConsumer
. Both of them
can be extended:
Passing connection params
Connection parameters can be passed using the connection_params
parameter of
the GraphQLWebsocketCommunicator
class. This is particularily useful to test
websocket authentication.
GraphQLHTTPConsumer (HTTP)
Options
GraphQLHTTPConsumer
supports the same options as all other integrations:
-
schema
: mandatory, the schema created bystrawberry.Schema
. -
graphql_ide
: optional, defaults to"graphiql"
, allows to choose the GraphQL IDE interface (one ofgraphiql
,apollo-sandbox
orpathfinder
) or to disable it by passingNone
. -
allow_queries_via_get
: optional, defaults toTrue
, whether to enable queries viaGET
requests -
multipart_uploads_enabled
: optional, defaults toFalse
, controls whether to enable multipart uploads. Please make sure to consider the security implications mentioned in the GraphQL Multipart Request Specification when enabling this feature.
Extending the consumer
We allow to extend GraphQLHTTPConsumer
, by overriding the following methods:
-
async def get_context(self, request: ChannelsRequest, response: TemporalResponse) -> Context
-
async def get_root_value(self, request: ChannelsRequest) -> Optional[RootValue]
-
async def process_result(self, request: Request, result: ExecutionResult) -> GraphQLHTTPResponse
. -
async def render_graphql_ide(self, request: ChannelsRequest) -> ChannelsResponse
Context
The default context returned by get_context()
is a dict
that includes the
following keys by default:
-
request
: AChannelsRequest
object with the following fields and methods:-
consumer
: TheGraphQLHTTPConsumer
instance for this connection -
body
: The request body -
headers
: A dict containing the headers of the request -
method
: The HTTP method of the request -
content_type
: The content type of the request
-
-
response
ATemporalResponse
object, that can be used to influence the HTTP response:-
status_code
: The status code of the response, if there are no execution errors (defaults to200
) -
headers
: Any additional headers that should be send with the response
-
render_graphql_ide
In case you need more control over the rendering of the GraphQL IDE than the
graphql_ide
option provides, you can override the render_graphql_ide
method.
GraphQLWSConsumer (WebSockets / Subscriptions)
Options
-
schema
: mandatory, the schema created bystrawberry.Schema
. -
debug
: optional, defaults toFalse
, whether to enable debug mode. -
keep_alive
: optional, defaults toFalse
, whether to enable keep alive mode for websockets. -
keep_alive_interval
: optional, defaults to1
, the interval in seconds for keep alive messages.
Extending the consumer
We allow to extend GraphQLWSConsumer
, by overriding the following methods:
-
async def get_context(self, request: ChannelsConsumer, connection_params: Any) -> Context
-
async def get_root_value(self, request: ChannelsConsumer) -> Optional[RootValue]
Context
The default context returned by get_context()
is a dict
and it includes the
following keys by default:
-
request
: TheGraphQLWSConsumer
instance of the current connection. It can be used to access the connection scope, e.g.info.context["ws"].headers
allows access to any headers. -
ws
: The same asrequest
-
connection_params
: Anyconnection_params
, see Authenticating Subscriptions
Example for defining a custom context
Here is an example for extending the base classes to offer a different context
object in your resolvers. For the HTTP integration, you can also have properties
to access the current user and the session. Both properties depend on the
AuthMiddlewareStack
wrapper.
You can import and use the extended GraphQLHTTPConsumer
and
GraphQLWSConsumer
classes in your myproject.asgi.py
file as shown before.
API
GraphQLProtocolTypeRouter
A helper for creating a common strawberry-django
ProtocolTypeRouter
Implementation.
Example usage:
This will route all requests to /graphql on either HTTP or websockets to us, and everything else to the Django application.
ChannelsConsumer
Strawberries extended
AsyncConsumer
.
Every graphql session will have an instance of this class inside
info.context["ws"]
(WebSockets) or info.context["request"].consumer
(HTTP).
properties
-
type
- The type of the message to wait for, equivalent toscope['type']
-
timeout
- An optional timeout to wait for each subsequent message. -
groups
- list of groups to yield messages from threw channel layer.