I have this script which receive the message and send the same message to the all connected browser.
comsumer.py
import json
from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
from .models import Message
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_group_name = 'chat'
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def push(self,message):
print("pushing message")
await self.send(text_data=json.dumps({
'message': message
}))
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
res = await self.save_message_to_db(message)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': res['message_data'],
}
)
async def chat_message(self, event):
message = event['message']
# WebSocketを介してメッセージを送信
await self.send(text_data=json.dumps({
'message': message
}))
@database_sync_to_async
def save_message_to_db(self, message_text):
message = Message.objects.create(content=message_text)
return {
'message_data': {
'id': message.id,
'content': message.content,
'timestamp': message.timestamp.isoformat(),
}
}
And, this class is used as
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/', consumers.ChatConsumer.as_asgi()),
]
Now, I want to call async def push()
from view or command script.
For now, I am testing in management/commands/test_cmd.py
from chat.consumers import ChatConsumer
.
.
.
chatConsumer = ChatConsumer()
asyncio.run(chatConsumer.push("testtest"))
This shows the error like this below.
I guess I should init ChatConsumer(AsyncWebsocketConsumer)
in a defferent way,
How can I fix this??
Traceback (most recent call last):
File "/Users/bear/MyCode/httproot/websocketdjango/manage.py", line 22, in <module>
main()
File "/Users/bear/MyCode/httproot/websocketdjango/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
utility.execute()
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/django/core/management/__init__.py", line 436, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/django/core/management/base.py", line 413, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/django/core/management/base.py", line 459, in execute
output = self.handle(*args, **options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/bear/MyCode/httproot/websocketdjango/chat/management/commands/test_cmd.py", line 44, in handle
asyncio.run(chatConsumer.push("testtest"))
File "/opt/homebrew/Cellar/[email protected]/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/[email protected]/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/[email protected]/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/Users/bear/MyCode/httproot/websocketdjango/chat/consumers.py", line 28, in push
await self.send(text_data=json.dumps({
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/channels/generic/websocket.py", line 218, in send
await super().send({"type": "websocket.send", "text": text_data})
File "/Users/bear/.local/share/virtualenvs/websocketdjango-9al5Z1lH/lib/python3.12/site-packages/channels/consumer.py", line 81, in send
await self.base_send(message)
^^^^^^^^^^^^^^
AttributeError: 'ChatConsumer' object has no attribute 'base_send'