Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django websockets implementation

I'm new to python and Django and i'm trying to implement websockets in Django.
What i do is i'm following the steps described in websockets documentation
The problem is that the server side command described has to be run in console. When i run it from console it works, but i want to run it inside the Django view asynchronously with a GET request. When i try it the server raises an exception something like this RuntimeError: There is no current event loop in thread 'Thread-2'.
To be more specific I want to use the technology to show a real time logs. For example an oracle procedure performs an insert and server pushes it to a page with websockets.
Am I on a wrong path for implementing the described or can anyone suggest a right/better solution?

I'm on django version 1.9 implemented on both Django's development server and Uwsgi and Nginx server, python version 3.5.2 on RedHatEnterpriseServer Release: 6.7


UPDATE
The exact code from the above URL and i put it in the view.

def ws(request):

    async def time(websocket, path):
        while True:
            now = datetime.datetime.utcnow().isoformat() + 'Z'
            await websocket.send(now)
            await asyncio.sleep(random.random() * 3)

    start_server = websockets.serve(time, '192.168.4.177', 9876)

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

return render(request,"ws.html")

When the URL is handled by this view the above mentioned error occurs.

My ws.html is the exact copy from the above mentioned websockets documentation example

like image 800
arminrock Avatar asked Nov 22 '25 06:11

arminrock


1 Answers

Django's request/response cycle is strictly synchronous. What you are trying to do is not possible in a normal Django view.

You might be interested in Django Channels, a project that aims to remove this limitation.

like image 163
jaap3 Avatar answered Nov 24 '25 19:11

jaap3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!