DjangoChannelsGraphqlWs icon indicating copy to clipboard operation
DjangoChannelsGraphqlWs copied to clipboard

How do I get access to `scope` in when calling `broadcast`?

Open chidimo opened this issue 3 years ago • 0 comments

This is actually not an issue, but I couldn't find anything in the example app that helps me.

From the example app, I got a hold of the on_connect method of the consumer where I pass the frontend client URL. This URL can be passed directly from apollo client WebSocket link.

    async def on_connect(self, payload):
        """New client connection handler."""
        self.scope['domain'] = payload.get('domain')
        print(f"Connected to {self.channel_name}")

My subscription class definition starts out as

class OnChangeUserAccess(channels_graphql_ws.Subscription):

In the subscribe and publish methods of my subscriptions, I attempt to attach the domain to the class like below.

    def subscribe(self, info, email):
        _scope = info.context._scope
        domain = _scope.get('domain')

        OnChangeUserAccess.domain = domain # this line doesn't seem to do anything. Works sometimes and fails other times.

        return [domain]

I then define a class method that broadcasts some change to subscribers.

    @classmethod
    def broadcast_change(cls, email):
       # email is passed directly to the method at the point of call.

        domain = cls.domain # Error, OnChangeUserAccess has no property domain

        user_access = evaluate_access(domain, email)
        cls.broadcast(
            group=email,
            payload={"user_access": user_access},
        )

I could pass the domain directly to the broadcast_change method, but that would just repeat code needlessly in a lot of places, some of them requiring DB access.

My question is, is there a way to get a hold of the scope (or at least the domain) in the broadcast_change method so I can read the domain off of it?

Thanks for any and every help.

chidimo avatar Mar 02 '21 14:03 chidimo