I am trying to build a simple chat app using Django Channels 2.4.0, here is my consumer code:
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
if "session_str" in self.scope["session"]:
# get chat history
else:
#create a new chat room
await self.accept()
I am not sure how I can set the session string when I'm test with AsyncWebsocketConsumer. I have tried below method
@pytest.mark.asyncio
async def test_ws_connection(self):
""" Test initial websocket connection
"""
start_datetime = datetime.datetime.now()
test_room = Room(create_datetime=start_datetime)
session_str = test_room.session_str
client = Client()
client.session["session_str"] = session_str
application = URLRouter([
url(r'ws/chat/$', ChatConsumer),
])
communicator = WebsocketCommunicator(application, "ws/chat/")
connected, _ = await communicator.connect()
assert connected
await communicator.disconnect()
I got the following error on line: client.session["session_str"] = session_str
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
Any help will be appreciated!
Aucun commentaire:
Enregistrer un commentaire