TypeError: объект 'NoneType' не является вызываемым django websockets
я пытаюсь добавить функцию уведомления в мой проект. но когда я пытаюсь подключиться с помощью postman, я получаю TypeError: 'NoneType' object is not callable. я понятия не имею, почему я получаю эту ошибку. ошибка даже не указывает на строку в моем коде. это мой consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class NotificationConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['user_id']
user = self.scope['user']
if self.room_name == user:
async_to_sync(self.channel_layer.group_add)(
self.room_name,
self.channel_name
)
self.accept()
return
async def disconnect(self, code):
return await self.close()
def receive(self, text_data=None):
return
def send_notifications(self, event):
data = json.loads(event.get('value'))
self.send(text_data=json.dumps({'payload':data}))
вот мой routing.py
from django.urls import re_path
from .consumers import NotificationConsumer
websocket_urlpatterns = [
re_path(r'ws/notification/(?P<user_id>\w+)/$', NotificationConsumer.as_asgi()),
]
это мой channelsmiddleware.py
from django.db import close_old_connections
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from jwt import decode as jwt_decode
from clothRentalBackend import settings
from django.contrib.auth import get_user_model
from urllib.parse import parse_qs
class TokenAuthMiddleware:
"""
Custom token auth middleware
"""
def __init__(self, inner):
# Store the ASGI application we were passed
self.inner = inner
def __call__(self, scope):
# Close old database connections to prevent usage of timed out connections
close_old_connections()
# Get the token
token = parse_qs(scope["query_string"].decode("utf8")).get("token")[0]
try:
UntypedToken(token)
except (InvalidToken, TokenError) as e:
print(e)
return None
else:
decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"])
user = get_user_model().objects.get(id=decoded_data["id"])
return self.inner(dict(scope, user=user))
Я получаю следующую ошибку, когда пытаюсь подключиться, передав токен по адресу ws://localhost:8000/ws/notification/1/?token=<jwt_token>
error:
WebSocket HANDSHAKING /ws/notification/1/ [127.0.0.1:37906]
Token has no id
Exception inside application: 'NoneType' object is not callable
Traceback (most recent call last):
File "/home/rijan/Desktop/projects/fyp/django/clothRentalBackend/env/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__
return await self.application(scope, receive, send)
File "/home/rijan/Desktop/projects/fyp/django/clothRentalBackend/env/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__
return await application(scope, receive, send)
File "/home/rijan/Desktop/projects/fyp/django/clothRentalBackend/env/lib/python3.8/site-packages/asgiref/compatibility.py", line 34, in new_application
return await instance(receive, send)
TypeError: 'NoneType' object is not callable
WebSocket DISCONNECT /ws/notification/1/ [127.0.0.1:37906]