我最近开始学习websockets,我决定尝试学习并使用Python的framweork Tornado来创建我的简单测试项目(没有什么特别的,只是基本的项目,可以帮助我了解一些关于Tornado和websockets的知识)。在
所以,这是我的想法(工作流程):
1)我收到来自其他应用程序的http post请求到我的服务器(例如,关于某人姓名和电子邮件的信息)
2)我将接收到的数据保存到postgresql数据库中,并通知侦听器(发布/订阅)新数据已添加到数据库中
3)接收到通知后,服务器应向客户端发送消息(write-_ng-message方法)
这是我现在的密码
简单_服务器.pyimport 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()
当我测试将post请求(通过Postman REST客户端)发送到定义的url时,一切正常。数据真的被保存到我的数据库,它真的通知侦听器有新的通知,但我只是不知道如何在那之后将该消息发送给客户端。
如果我能做到这一点,它就会在浏览器中显示这条信息,这就是我这次想要做的。在
所以,我只想在收到关于数据库中新条目的通知后调用write峎message函数(而不是仅仅打印“new notify message”),但我不知道如何在Tornado中执行。
我相信这应该是非常容易的,但由于我显然缺乏Tornado(和异步编程)的经验,我有点卡住了。在
谢谢你的帮助