I try to implement simple graphql subscription on FastAPI.
According to documentations but it is not working
import asyncio
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
from graphql.execution.executors.asyncio import AsyncioExecutor
from starlette.websockets import WebSocket
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
async def resolve_hello(self,info,name):
return "Hello " + name
class Subscription(graphene.ObjectType):
count = graphene.Int(upto=graphene.Int())
async def subscribe_count(root, info, upto=3):
for i in range(upto):
yield i
await asyncio.sleep(1)
app = FastAPI()
schema = graphene.Schema(query=Query, subscription=Subscription)
app.add_route("/", GraphQLApp(schema=schema, executor_class=AsyncioExecutor))
I googled and found that i might need to implement subscription-server like for Sanic or Aiohttp
I try but it doesn't work yet
from graphql_ws.websockets_lib import WsLibSubscriptionServer
subscription_server = WsLibSubscriptionServer(schema)
@app.websocket("/subscriptions")
async def subscriptions(websocket: WebSocket):
await subscription_server.handle(websocket)
return websocket
Error recieve:
return self.ws.open is False
AttributeError: 'WebSocket' object has no attribute 'open'
What i'm doing wrong and how it could be solved? Thank you.