[英]How can I add data to PostgreSQL in real-time chatbot based on Django websockets?
I am trying to create real-time chat using Django back-end and Angular 4 front-end with PostgreSQL database. 我正在尝试使用Django后端和Angular 4前端以及PostgreSQL数据库创建实时聊天。 Let's assume that I would like to create chat robot for instance like ALICE . 假设我想创建一个聊天机器人,例如ALICE 。 It seems to me that the most optimal solution would be to use websockets? 在我看来,最佳的解决方案是使用websockets? I create channel layer using Redis . 我使用Redis创建通道层。 Now, I would like to save all messages to my PostgreSQL database. 现在,我想将所有消息保存到我的PostgreSQL数据库中。 I wonder how it should be done. 我不知道应该怎么做。 Should I create models and use them in consumers.py
or maybe there is an another more optimal way? 我应该创建模型并在consumers.py
使用它们,还是有另一种更优化的方法? In the future I would like to analyze data from database and return the answer. 将来,我想分析数据库中的数据并返回答案。
consumers.py: users.py:
# In consumers.py
from channels import Group
# Connected to websocket.connect
def ws_connect(message):
# Accept the connection
message.reply_channel.send({"accept": True})
# Add to the chat group
Group("chat").add(message.reply_channel)
# Connected to websocket.receive
def ws_receive(message):
Group("chat").send({
"text": message.content['text'],
})
print(message.content['text'])
# Connected to websocket.disconnect
def ws_disconnect(message):
Group("chat").discard(message.reply_channel)
routing.py: routing.py:
from channels.routing import route
from backend.consumers import ws_connect, ws_receive, ws_disconnect
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
settings.py: settings.py:
CHANNEL_LAYERS = {
"default": {
# This example app uses the Redis channel layer implementation asgi_redis
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [(redis_host, 6379)],
},
"ROUTING": "backend.routing.channel_routing",
},
}
I had the same issue, so create a model in your models.py
for example Message
model. 我遇到了同样的问题,因此请在您的models.py
创建一个模型,例如Message
模型。
class Message(models.Model):
message = models.TextField()
and import it to consumers.py
并将其导入consumers.py
#consumers.py
from .models import Message
def ws_receive(message):
Group("chat").send({
"text": message.content['text'],
})
msg = Message()
msg.message = message.content['text']
msg.save()
But if you will use this snippet in production, it will hit your database performance. 但是,如果你将在生产中使用这个片段中,它会打你的数据库的性能。 But as I heard, you can make some kind of queue with python module multiprocessing and save messages from that queue. 但是,正如我所听到的,您可以使用python模块进行多处理来创建某种队列,并保存该队列中的消息。 I haven't seen implementation with custom queues, so you should make your own. 我还没有看到使用自定义队列的实现,因此您应该自己创建队列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.