我正在学习Django,我正在一个网页上工作,我需要为用户提供登录外部服务的可能性。我不能简单地使用传统的Django视图系统,否则,我会通过简单的刷新失去连接。出于这个原因,我想到了使用Django Channels。
我现在的问题是如何将数据发送到消费者类?使用consumers.py
中给出的tutorial,我想将表单提交中的数据发送到connect
函数,然后如果登录到外部服务就可以建立连接。然后,在那种情况下,我可以使用client
instance和这些外部服务的方法。
那么,简而言之,是否有可能向消费者发送表单数据?对于敏感数据的安全性,这样可以吗?
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
######
## login to external service
######
#get login data from form submited when the websockted is initiated
username = ...
pass = ...
self.client = Client(username, password)
if client:
await self.accept()
# Receive message from room group
async def chat_message(self, event):
message = event['message']
self.client.send(event['message'])
更新:
To clear the explanation: I can't save the user username and pass of the external service, and that I want to offer the user the possibility to use this [sms service](https://clxcommunications.github.io/sdk-xms-python/tutorial.html) with a text field and phone number.
所以问题是即使我创建了一个表单和用户名和密码来登录(在视图中)
client = clx.xms.Client('myserviceplan', 'mytoken')
然后在下一个请求中,我将失去client
实例。这就是我想到Django Channels
的原因。但我不确定它是不是最好的解决方案......
通常,您可以通过以下方式从外部代码调用使用者中的方法:
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
await self.channel_layer.send(
'<channel_name>',
{
'type': '<method_name>',
}
)
但是正如您所看到的,这要求您指定在客户端连接后才能获得的通道名称。换句话说,您不应该尝试在消费者中调用connect而是其他一些方法。此外,您的客户端应该在最终访问之前首先连接到websocket。我不完全理解你的用例,但我希望这会给你一个想法