Using multiple Asgi apps in a project with custom middleware

Hi,

I am trying to implement a Projects with multiple Apps, with different WebSocket endpoints.

The below code, obviously does not work, but its for reference on what i am intending to do.

application = ProtocolTypeRouter(
    {
        'http': get_asgi_application(),
        'websocket': TokenAuthMiddleWare(AuthMiddlewareStack(URLRouter(websocket_urlpatterns))),
        'websocket': AuthMiddlewareStack(URLRouter(live_websocket_urlpatterns)),
    }
)

The websocket_urlpatterns is the projects internal WebSocket which is authenticated.
while live_websocket_urlpatterns is from a third party socket providers, which i do not intend to use authentication.

is there any pointers where I could accomplish this.?

thank you.

You should be able to use a URLRouter to branch to the two different websocket protocol handling apps, based on URL. (Otherwise you’d need to implement a custom routing middleware to use some other aspect of the request to route by.)

Thanks, I’ve tried it, however what I am trying to do is, set different WebSocket routing patterns for different paths.

for websocket_urlpatterns I am using a custom middleware TokenAuthMiddleWare,
and for live_websocket_urlpatterns I do not want the custom middleware.

Hi,
I think I managed to make it work, please check if the following snippet is a safe way to do the WebSocket routing:

# asgi.py
from api.routing import websocket_urlpatterns as api_app
from tracker.routing import live_websocket_urlpatterns as live_tracker
from api.middleware import TokenAuthMiddleWare


application = ProtocolTypeRouter(
    {
        'http': get_asgi_application(),
        'websocket': TokenAuthMiddleWare(AuthMiddlewareStack(URLRouter(api_app))),
    }
)
application = ProtocolTypeRouter(
    {
        'http': get_asgi_application(),
        'websocket': AuthMiddlewareStack(URLRouter(live_tracker)),
    }
)

thanks.