Helpers for using WebSockets in Django
Project description
django-ws
Helpers for using WebSockets in Django
Installation
pip install django-ws
Setup
asgi.py
- Remove line:
from django.core.asgi import get_asgi_application
- Remove line:
application = get_asgi_application()
Add to the end:
from django_ws import get_websocket_application
application = get_websocket_application()
ws_urls.py
Next to your root urls.py
create a ws_urls.py
like the example below that uses your websocket.
from django.urls import path
import myapp.ws
urlpatterns = [
path('ws', myapp.ws.MySocket),
]
Write a WebSocket
from django_ws import WebSocketHandler
class MySocket(WebSocketHandler):
async def on_open(self):
do_something_on_open()
async def on_message(self, data):
do_something_on_msg()
# send json data
self.send({"reply": "sending data back"})
async def on_close(self):
do_something_on_close()
More Features
start_ping method
Usage: self.start_ping()
Sends a ping {'ping': timezone.now().isoformat()}
every 59 seconds to keep the websocket alive. Sometimes this is needed with certain deployment environments.
start_task method
Usage: self.start_task(<task_id>, <coroutine>)
Example: self.start_task('send_weather', self.send_weather)
Creates an asyncio background task. django-ws
handles tracking duplicate tasks by ID and cancelling tasks during interruptions such as disconnects. Note: you still need to be careful about long running processing. Even if you await
a long running function, it will block the socket from closing. So do things in small chunks that can be interrupted.
sleep_loop method
Usage: await self.sleep_loop(<coroutine>, <seconds:int>)
Example: await self.sleep_loop(self._send_weather, 60 * 3)
Does an infinite loop and sleeps for the given seconds after each sleep. Uses an async sleep so that it does not block other tasks.
Middleware
Websockets in general follow a different lifecycle then HTTP requests.
This means websockets in Django do not have a pre-established middleware mechanism. However, middleware is still helpful with websockets.
Websocket Middleware
The websocket middleware functions much like the standard Django request/response middleware; however, since websockets open a long lived connection and messages are received and sent asynchronously it works slightly different.
This middleware is good for authenticating the initial websocket connections, and performing setup and tear down.
Websocket middleware setup in settings.py
:
WS_MIDDLEWARE = [
'myproject.middleware.AuthAsyncMiddleware',
]
Example middleware:
from importlib import import_module
from asgiref.sync import sync_to_async
from django.contrib import auth
from django.conf import settings
class AuthAsyncMiddleware:
def __init__(self, func):
self.func = func
async def __call__(self, ws):
print('Pre Run Loop')
if not hasattr(ws.request, 'user'):
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
session_key = ws.request.COOKIES.get(settings.SESSION_COOKIE_NAME)
ws.request.session = SessionStore(session_key)
ws.request.user = await sync_to_async(auth.get_user)(ws.request)
print('USER:', ws.request.user)
ret = await self.func(ws)
print('POST Run Loop')
return ret
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file django_ws-1.0.2.tar.gz
.
File metadata
- Download URL: django_ws-1.0.2.tar.gz
- Upload date:
- Size: 5.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.10.4 CPython/3.10.12
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 42aa6bccc82658c32e1cdb33b4770e876c9a99e8f058895747f0aeedd3687c4e |
|
MD5 | 3db670022f515c05c27d1c245fad7cc1 |
|
BLAKE2b-256 | e410e1bf1e78475f694f5904dbdadba48471f262b82e09a240e1c5a281d190f2 |
Provenance
File details
Details for the file django_ws-1.0.2-py3-none-any.whl
.
File metadata
- Download URL: django_ws-1.0.2-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.10.4 CPython/3.10.12
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6df0409bc145bdff3dc2e966fd0d437752085d4743f8ceb9be6e623ebf9d403e |
|
MD5 | f11c340be6330dc4de4e944c2ece430c |
|
BLAKE2b-256 | 955e75183ca31ba5673cadd8295ea0b7b7817c527fbe7d8120869f1978fd2336 |