9.Subscriptions订阅
The graphene-django
project does not currently support GraphQL subscriptions out of the box. However, there are several community-driven modules for adding subscription support, and the provided GraphiQL interface supports running subscription operations over a websocket.
“graphen -django”项目目前还不支持开箱即用的GraphQL订阅。但是,有几个社区驱动的模块用于添加订阅支持,并且所提供的GraphiQL接口支持在websocket上运行订阅操作。
To implement websocket-based support for GraphQL subscriptions, you’ll need to do the following:
要实现基于websocket的对GraphQL订阅的支持,你需要做以下工作:
- Install and configure django-channels. 安装和配置django-channels。
- Install and configure* a third-party module for adding subscription support over websockets. A few options include: 安装和配置*一个第三方模块,用于在websockets上增加订阅支持。一些选择包括:
- Ensure that your application (or at least your GraphQL endpoint) is being served via an ASGI protocol server like daphne (built in to
django-channels
), uvicorn, or hypercorn. 确保你的应用程序(或者至少你的GraphQL端点)是通过像daphne(内置到django-channels
)、uvicorn或hypercorn这样的ASGI协议服务器提供服务的。
*** Note:** By default, the GraphiQL interface that comes with
graphene-django
assumes that you are handling subscriptions at the same path as any other operation (i.e., you configured bothurls.py
androuting.py
to handle GraphQL operations at the same path, like/graphql
).*注意:默认情况下,
graphene-django
附带的GraphiQL接口假设您在与其他操作相同的路径上处理订阅(例如,您将urls.py
和routing.py
配置为在同一路径上处理GraphQL操作,如/graphql
)。If these URLs differ, GraphiQL will try to run your subscription over HTTP, which will produce an error. If you need to use a different URL for handling websocket connections, you can configure
SUBSCRIPTION_PATH
in yoursettings.py
:如果这些url不同,GraphiQL将尝试通过HTTP运行您的订阅,这将产生一个错误。如果你需要使用一个不同的URL来处理websocket连接,你可以在你的
settings.py
中配置SUBSCRIPTION_PATH
:GRAPHENE = { # ... "SUBSCRIPTION_PATH": "/ws/graphql" # The path you configured in `routing.py`, including a leading slash. }
Once your application is properly configured to handle subscriptions, you can use the GraphiQL interface to test subscriptions like any other operation.
一旦您的应用程序被正确地配置为处理订阅,您就可以像其他操作一样使用GraphiQL接口来测试订阅。