Django 频道 + 在发布请求后发送 websocket 消息
Posted
技术标签:
【中文标题】Django 频道 + 在发布请求后发送 websocket 消息【英文标题】:Django channels + send websocket message after post request 【发布时间】:2021-07-12 06:41:47 【问题描述】:我的应用程序有问题。我的 django 频道和 websocket 工作得非常好,当我从 JS(内部呈现的 html)发送消息时,消息将进入 websocket,然后进入数据库(异步)。但是当我尝试在 POST 请求渲染之前发送消息时,它会引发错误。
#here everything works fine:
def room(request, room_name):
messages = message.objects.all()
texts = []
for i in messages:
texts.append(i.text)
last_lines = texts[-20:]
vars =
"room_name": room_name,
"messages": last_lines,
print()
if request.method == "POST":
vars["post_d"] = request.POST.get("desc")
print(vars["post_d"])
# ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/")
# time.sleep(2)
# ws.send(json.dumps("message": message))
return render(request, "chat/room.html", vars)
return render(request, "chat/room.html", vars)
#=======================================================
System check identified no issues (0 silenced).
July 12, 2021 - 08:26:23
Django version 3.1.3, using settings 'onionChat.settings'
Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Post request from c# console app
HTTP POST /chat/loobby/ 200 [0.10, 127.0.0.1:3261]
我的发送 python websocket 消息的 test.py 文件(也很好用)更改显示在 web 浏览器的 db 和 websocket 中。
import json
import time
import asyncio
from websocket import create_connection
async def send(message):
ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/")
time.sleep(2)
ws.send(json.dumps("message": message))
print("here")
if __name__ == "__main__":
asyncio.run(send("nothing"))
#==================================================================
System check identified no issues (0 silenced).
July 12, 2021 - 08:29:48
Django version 3.1.3, using settings 'onionChat.settings'
Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
WebSocket HANDSHAKING /ws/chat/loobby/ [127.0.0.1:1032]
WebSocket CONNECT /ws/chat/loobby/ [127.0.0.1:1032]
WebSocket DISCONNECT /ws/chat/loobby/ [127.0.0.1:1032]
added message to db
但是当我尝试发送 websocket 消息并且在返回渲染之后它会抛出一个错误
def room(request, room_name):
messages = message.objects.all()
texts = []
for i in messages:
texts.append(i.text)
last_lines = texts[-20:]
vars =
"room_name": room_name,
"messages": last_lines,
print()
if request.method == "POST":
vars["post_d"] = request.POST.get("desc")
print(vars["post_d"])
ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/")
time.sleep(2)
ws.send(json.dumps("message": message))
return render(request, "chat/room.html", vars)
#==================================================================
System check identified no issues (0 silenced).
July 12, 2021 - 08:34:51
Django version 3.1.3, using settings 'onionChat.settings'
Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Post request from c# console app
WebSocket HANDSHAKING /ws/chat/loobby/ [127.0.0.1:30427]
WebSocket DISCONNECT /ws/chat/loobby/ [127.0.0.1:30427]
Internal Server Error: /chat/loobby/
Traceback (most recent call last):
File "C:\Program Files\Python39\lib\site-packages\asgiref\sync.py", line 339, in thread_handler
raise exc_info[1]
File "C:\Program Files\Python39\lib\site-packages\django\core\handlers\exception.py", line 38, in inner
response = await get_response(request)
File "C:\Program Files\Python39\lib\site-packages\django\core\handlers\base.py", line 231, in _get_response_async
response = await wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files\Python39\lib\site-packages\asgiref\sync.py", line 304, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "C:\Program Files\Python39\lib\asyncio\tasks.py", line 442, in wait_for
return await fut
File "C:\Program Files\Python39\lib\concurrent\futures\thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Program Files\Python39\lib\site-packages\asgiref\sync.py", line 343, in thread_handler
return func(*args, **kwargs)
File "C:\Users\Алексей\Desktop\dev\OnionChat\onionChat\chat\views.py", line 48, in room
ws = create_connection("ws://127.0.0.1:8000/ws/chat/loobby/")
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_core.py", line 595, in create_connection
websock.connect(url, **options)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_core.py", line 252, in connect
self.handshake_response = handshake(self.sock, *addrs, **options)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_handshake.py", line 59, in handshake
status, resp = _get_resp_headers(sock)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_handshake.py", line 143, in _get_resp_headers
status, resp_headers, status_message = read_headers(sock)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_http.py", line 300, in read_headers
line = recv_line(sock)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_socket.py", line 136, in recv_line
c = recv(sock, 1)
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_socket.py", line 115, in recv
bytes_ = _recv()
File "C:\Users\Алексей\AppData\Roaming\Python\Python39\site-packages\websocket\_socket.py", line 92, in _recv
return sock.recv(bufsize)
ConnectionResetError: [WinError 10054] Удаленный хост принудительно разорвал существующее подключение
HTTP POST /chat/loobby/ 500 [4.97, 127.0.0.1:30426]
还有我的 c# 代码,但我认为问题不在这里
static void post_command(string command)
using (var client = new WebClient())
client.Timeout = 600 * 60 * 1000;
client.Headers["User-Agent"] = "Mozilla/5.0";
var values = new NameValueCollection();
values["desc"] = $"command";
client.UploadValues(link, values);
//var responseString = Encoding.Default.GetString(response);
//Console.Write(responseString);
【问题讨论】:
【参考方案1】:我知道这是一个相当老的问题,尽管我现在面临同样的问题。 似乎无法从已经提供此类连接的应用程序打开 web-socket 连接。这就是您的 test.py 有效的原因 - 因为它在 Django 应用程序之外。
所以我想出了从当前打开的套接字中获取相关通道的解决方案:
views.py
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
def room(request, room_name):
# your logic...
if request.method == "POST":
vars["post_d"] = request.POST.get("desc")
print(vars["post_d"])
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f'chat_room_name',
'type': 'receive',
'message': message
)
假设在 routing.py 你有:
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
在您的 consumers.py 中,您必须相应地匹配 receive
方法(注意 type='receive'
)和您的 channel
名称(在您的示例中是 lobby )
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'chat_self.room_name'
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def receive(self, text_data=None, type='receive', **kwargs):
if isinstance(text_data, dict):
text_data_json = text_data
else:
text_data_json = json.loads(text_data)
# all other logic on handling the message...
【讨论】:
以上是关于Django 频道 + 在发布请求后发送 websocket 消息的主要内容,如果未能解决你的问题,请参考以下文章
“发送非空 'Sec-WebSocket-Protocol' 标头但未收到响应” Django 频道