问题描述
我正在尝试对Django Channels应用程序的connect方法中的单独django CRUD API应用程序进行获取请求
所以在consumers.py内部,我正在这样做
class AssistantConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.commands = requests.get('http://localhost:8000/api/commands')
print(self.commands)
这样做会导致websocket卡住
WebSocket HANDSHAKING /ws/assistant/user/ [127.0.0.1:64374]
谁能告诉我为什么?
该API本身正在发挥作用,我正在从React(它也连接到Websocket)发布到它。一切正常-我只需要从使用者的数据库中获取一些数据。
关于这种情况的任何地方都找不到。
解决方法
好的,我找到了一个解决方案-不知道它是正确的还是稳定的,但是PyPi上的这个软件包可以解决问题。
https://pypi.org/project/requests-async/
感谢Timothee指出我需要异步进行此操作。
这现在有效。
import requests_async as requests
async def connect(self):
self.commands = await requests.get('http://localhost:8000/api/commands/')
print(self.commands)
await self.accept()
也许这会帮助其他人,如果有人知道我不应该这样做的原因,我很想知道。
, async def connect
仅在客户端尝试连接并且路由文件将传入连接发送到AssistantConsumer
时调用。在您的情况下,您将陷入最初的“握手”。这意味着您正在接收来自客户端的连接请求,但是您不接受该连接,因此WebSocket连接永远不会打开。
添加await self.accept()
应该接受传入的连接,因此打开WebSocket。
是这样的:
class AssistantConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.commands = requests.get('http://localhost:8000/api/commands')
print(self.commands)
await self.accept()