Is it possible to use channel to proxy to another upstream server? #1755
-
I want to use Django to do permission checking and then establish a websocket proxy to an upstream server, is it possible? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
Hi. I would suspect so yes. You'd need an async websocket client, and then feed the messages to/from that back out from your consumer. I'm afraid there's nothing built-in to do that as you, but it would be interesting to see what you come up with. |
Beta Was this translation helpful? Give feedback.
-
Because I needed to proxify a Jupyter Notebook trough a Django app, here my solution imoprt asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
from websockets import client as ws_client
class AsyncWebsocketProxyConsumer(AsyncWebsocketConsumer):
async def websocket_connect(self, message):
self.upstream = await ws_client.connect("ws://localhost:8888/bla/bla/bla")
asyncio.create_task(self.receive_upstream())
await super().accept(subprotocol)
async def disconnect(self, code):
await self.upstream.close()
return await super().disconnect(code)
async def receive(self, text_data=None, bytes_data=None):
await self.upstream.send(text_data)
async def receive_upstream(self):
async for message in self.upstream:
await self.send(message) Disclaimer: I have no idea of what I’m doing, but it’s work on my prod 🤷 |
Beta Was this translation helpful? Give feedback.
-
I saw Simon Willison released an https://github.com/simonw/asgi-proxy-lib There's an open ticket for WebSocket support: |
Beta Was this translation helpful? Give feedback.
-
@jtremesay-sereema what is |
Beta Was this translation helpful? Give feedback.
-
this worked for me https://gist.github.com/brianglass/e3184341afe63ed348144753ee62dce5 |
Beta Was this translation helpful? Give feedback.
Because I needed to proxify a Jupyter Notebook trough a Django app, here my solution