socket for api in django
Create a Django view to establish a WebSocket connection using channels.
- Install Channels package:
pip install channels
- Add 'channels' and 'yourapp' to
INSTALLED_APPS
in settings.py:
INSTALLED_APPS = [
...
'channels',
'yourapp',
...
]
- Create a consumers.py file in your app and define a WebSocket consumer:
from channels.generic.websocket import WebsocketConsumer
class YourConsumer(WebsocketConsumer):
def connect(self):
# Called on connection
pass
def disconnect(self, close_code):
# Called on disconnection
pass
def receive(self, text_data):
# Called when data is received
pass
- Create a routing file in your app:
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/your_url/', consumers.YourConsumer.as_asgi()),
]
- Include the routing configuration in your project's routing file (e.g.,
routing.py
):
from channels.routing import ProtocolTypeRouter, URLRouter
import yourapp.routing
application = ProtocolTypeRouter({
'websocket': URLRouter(
yourapp.routing.websocket_urlpatterns
),
})