Reputation: 14586
Thanks to the huge update 1.10, Django now supports async websockets. Awesome! I've used the websockets to connect a client to the Django server. Now I have a use case where the server needs to initialize a socket connection to another server.
Question: Is it possible for a Django backend to initialize a websocket connection to another server? If yes, how can is this done?
Upvotes: 2
Views: 133
Reputation: 2329
It is definitely possible to initialize a websocket connection from Django to a WS server. You can use a number of websocket packages such as https://websockets.readthedocs.io/en/stable/ to start a websocket client.
import asyncio
import websockets
async def hello():
async with websockets.connect('ws://localhost:8765') as websocket:
name = input("What's your name? ")
await websocket.send(name)
print("> {}".format(name))
greeting = await websocket.recv()
print("< {}".format(greeting))
asyncio.get_event_loop().run_until_complete(hello())
You should take care to decide where to put this code as websockets are by nature asynchronous.
Upvotes: 1