and_noob
and_noob

Reputation: 53

FastAPI and Graphene 3 subscriptions problem

How to make work subscriptions. I get 403 using simple graphql client like Altair. I didn't have any problems using graphene v.2 with aiohttp. Unfortunately graphql-ws doesn't go with graphene 3 and can't be used.

My code:

import asyncio
import graphene
import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette_graphene3 import GraphQLApp

class User(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()

class Query(graphene.ObjectType):
    me = graphene.Field(User)
    async def resolve_me(root, info):
        return {"id": "john", "name": "John"}

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)

middleware = [
    Middleware(
        TrustedHostMiddleware,
        allowed_hosts=['*'],
    ),
    Middleware(CORSMiddleware, allow_origins=['*'])
]

app = Starlette(debug=True, middleware=middleware)
schema = graphene.Schema(query=Query, subscription=Subscription)
app.mount("/graphql", GraphQLApp(schema))

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Укажите разрешенные домены
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    uvicorn.run(app, port=8000)   

Upvotes: 0

Views: 18

Answers (0)

Related Questions