gpt4 book ai didi

python - 收到通知后从服务器向客户端发送消息(Tornado+websockets)

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:47 26 4
gpt4 key购买 nike

我最近开始学习 websockets,我决定尝试学习和使用 Python 的 framweork Tornado 来创建我的简单测试项目(没什么特别的,只是基本项目,可以帮助我了解 Tornado 和 websockets 的一般知识) .

所以,这是我的想法(工作流程):

1)我从其他应用程序向我的服务器发送 http post 请求(例如有关某人的姓名和电子邮件的信息)

2) 我将收到的数据保存到我的 postgresql 数据库并通知监听器(发布/订阅)新数据已添加到数据库

3)服务器收到通知后应该向客户端发送消息(write_message方法)

这是我现在的代码

simple_server.py

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import psycopg2
import psycopg2.extensions
import os
from tornado.options import define, options

define("port", default=8000, help="run on the given port", type=int)

io_loop = tornado.ioloop.IOLoop.instance()

connection = psycopg2.connect('dbname=mydb user=myusername password=mypassword')
connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')

class ReceivedDataHandler(tornado.web.RequestHandler):
def post(self):
cursor = connection.cursor()

name=self.get_argument('name', 'No name info received')
email = self.get_argument('email', 'No email info received')
self.write("New person with name %s and email %s" %(name, email))

cursor.execute("INSERT INTO mydata VALUES (%s, %s)" %(name, email))
cursor.execute("NOTIFY test_channel;")

class EchoHandler(tornado.websocket.WebSocketHandler):
def open(self):
self.write_message('connected!')
def on_message(self, message):
self.write_message("Received info about new person: "+message)
def on_close(self):
print 'connection closed'

def listen():
cursor = connection.cursor()
cursor.execute("LISTEN test_channel;")

def receive(fd, events):
"""Receive a notify message from channel I listen."""
state = connection.poll()
if state == psycopg2.extensions.POLL_OK:
if connection.notifies:
notify = connection.notifies.pop()
print "New notify message"
io_loop.add_handler(connection.fileno(), receive, io_loop.READ)

if __name__=="__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[
(r'/', IndexHandler),
(r'/person-info', ReceivedDataHandler),
(r'/websocket', EchoHandler)
],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
listen()
io_loop.start()

当我测试发送发布请求(通过 Postman REST 客户端)到定义的 url 时,一切正常。数据确实保存到我的数据库中,它确实通知监听器有新通知,但我只是不知道之后如何将该消息发送给客户端。如果我能做到这一点,那么它就会在浏览器中显示该消息,这就是我这次想做的。

所以,我想做的实际上是在收到有关数据库中新条目的通知后调用 write_message 函数(而不是仅仅打印“新通知消息”),但我只是不知道如何在 Tornado 中执行此操作。我相信实际上应该很容易,但由于我显然缺乏 Tornado(和异步编程)的经验,所以我有点卡住了。

感谢您的帮助

最佳答案

最终我找到了解决这个问题的方法。我刚刚添加了全局变量,在其中添加所有连接的客户端,然后在收到通知时向每个连接的客户端发送消息。 (这对我来说没问题,因为我实际上想向所有连接的客户端发送消息)

这就是现在的样子

simple_server.py

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import psycopg2
import psycopg2.extensions
import os
from tornado.options import define, options

define("port", default=8000, help="run on the given port", type=int)

io_loop = tornado.ioloop.IOLoop.instance()

connection = psycopg2.connect('dbname=mydb user=myusername password=mypassword')
connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

# This is a global variable to store all connected clients
websockets = []

class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')

class ReceivedDataHandler(tornado.web.RequestHandler):
def post(self):
cursor = connection.cursor()

name=self.get_argument('name', 'No name info received')
email = self.get_argument('email', 'No email info received')
self.write("New person with name %s and email %s" %(name, email))

cursor.execute("INSERT INTO mydata VALUES (%s, %s)" %(name, email))
cursor.execute("NOTIFY test_channel;")

class EchoHandler(tornado.websocket.WebSocketHandler):
def open(self):
self.write_message('connected!')
def on_message(self, message):
self.write_message("Received info about new person: "+message)
def on_close(self):
print 'connection closed'

def listen():
cursor = connection.cursor()
cursor.execute("LISTEN test_channel;")

def receive(fd, events):
"""Receive a notify message from channel I listen."""
state = connection.poll()
if state == psycopg2.extensions.POLL_OK:
if connection.notifies:
notify = connection.notifies.pop()
for ws in websockets:
ws.write_message("my message")
io_loop.add_handler(connection.fileno(), receive, io_loop.WRITE)

if __name__=="__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
handlers=[
(r'/', IndexHandler),
(r'/person-info', ReceivedDataHandler),
(r'/websocket', EchoHandler)
],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
listen()
io_loop.start()

关于python - 收到通知后从服务器向客户端发送消息(Tornado+websockets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com