Django 频道 + Postgresql:实时数据库消息传递
我目前正在使用 Django 和 PostgreSQL 开发一个应用程序。通常,新信息被发送到数据库(有时一天一次,有时一天超过 30000 次)。我有一个 UI (vue.js),我想查看数据库中的数据实时显示给客户端。
目前我正在使用 Django Channels。我实现了 websocket 并使用 psycopg2 库来监听来自 postgresql 触发器的通知。我的消费者看起来像这样:
class WSConsumer(WebsocketConsumer):
def connect(self):
self.accept()
# the whole table is sent to the client after the connection
self.send(json.dumps(ClientSerializer(Client.objects.all(), many=True).data))
# connecting to database
conn = psycopg2.connect(dbname='...', user='...')
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN update_clients_table;")
# then I listen to any new data in this table and send it to the client
while True:
if select.select([conn],[],[],5) == ([],[],[]):
print("Timeout")
else:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
print("Got NOTIFY:", notify.pid, notify.channel, notify.payload)
message = notify.payload
self.send(message)
def disconnect(self):
self.close()
这是处理 1 个表中的更改的示例。我总共有 20 个表,大约 100 个可以连接到 websocket 的客户端。
我的问题:这是使用 Django 和 PostgreSQL 构建实时应用程序的好方法吗?是否简单、方便、安全?还有其他方法来构建这样的应用程序吗?
提前致谢!
I am currently developing an app with Django and PostgreSQL. Often, new information is sent to database (sometimes one time a day, sometimes over 30000 times a day). I have an UI (vue.js) and I want to see the data from the database showing to the client in real time.
Currently I am using Django Channels. I implemented websocket and used psycopg2 library to listen to notifications from postgresql triggers. My consumer looks like this:
class WSConsumer(WebsocketConsumer):
def connect(self):
self.accept()
# the whole table is sent to the client after the connection
self.send(json.dumps(ClientSerializer(Client.objects.all(), many=True).data))
# connecting to database
conn = psycopg2.connect(dbname='...', user='...')
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN update_clients_table;")
# then I listen to any new data in this table and send it to the client
while True:
if select.select([conn],[],[],5) == ([],[],[]):
print("Timeout")
else:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
print("Got NOTIFY:", notify.pid, notify.channel, notify.payload)
message = notify.payload
self.send(message)
def disconnect(self):
self.close()
This is an example of handling changes in 1 table. I have 20 tables in total, and around 100 clients that can connect to the websocket.
My question: is it a good way of building real-time app with Django and PostgreSQL? Is it simple, convenient, secure? Are there other ways to build such an app?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论