【发布时间】:2019-03-10 21:56:57
【问题描述】:
我正在学习 Django,我正在一个网页中工作,我需要为用户提供登录外部服务的可能性。我不能简单地使用传统的 Django 视图系统,否则我会因为简单的刷新而失去连接。出于这个原因,我考虑使用Django Channels。
我现在的问题是如何将数据发送到消费者类?使用tutorial 中给出的consumers.py,我想将表单提交中的数据发送到connect 函数,然后在登录到外部服务正常时进行连接。然后,在那种情况下,我可以使用 clientinstance 和来自这些外部服务的方法。
那么,简而言之,是否可以向消费者发送表单数据?对于敏感数据的安全性,这样可以吗?
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 的原因。但我不确定这是否是最好的解决方案......
【问题讨论】:
-
您可以将凭据缓存在浏览器中或作为 cookie。无论如何,如果你真的想使用通道来实现这一点,客户端必须首先通过 websocket 连接到服务器,然后你将他添加到由他的 id 或他独有的东西组成的组中。然后,当他提交表单时,您可以像我在下面所做的那样使用 channel_layer 在消费者中调用一些方法(不连接),该方法获取凭据并在客户端不存在时创建客户端。然后继续向服务发出所需的请求。不过,这是一种非常奇怪的方式
-
好的,感谢您的建议!
标签: python django chat django-channels