Python的一个新web框架Tornado的初步了解

jopen 7年前


        Python的一个新web框架,由非死book开源。不得不说,品牌效应啊,只要是非死book开源的项目,没有不好用的。Tornado可以说是好用到了极致,从打开官方页面开始了解,到搭建一个web服务器,只用了10分钟。

        另外,Tornado支持websocket通讯,和前几天看的通过Netty支持Websocket相比,Tornado的操作要显得简单得更多。

下载地址:http://www.tornadoweb.org/en/stable/

 

安装步骤:

tar xvzf tornado-3.0.1.tar.gz  cd tornado-3.0.1  python setup.py build  sudo python setup.py install

服务器代码如下:

import tornado.ioloop  import tornado.web  import tornado.websocket    class MainHandler(tornado.web.RequestHandler):      def get(self):          self.write("Hello, world")    class MainHandler2(tornado.web.RequestHandler):      def get(self):          self.write("This is a test")    class EchoWebSocket(tornado.websocket.WebSocketHandler):      def open(self):          print "WebSocket opened"        def on_message(self, message):          self.write_message(u"You said: " + message)        def on_close(self):          print "WebSocket closed"    application = tornado.web.Application([      (r"/", MainHandler),      (r"/test", MainHandler2),      (r"/websocket", EchoWebSocket),  ])    if __name__ == "__main__":      application.listen(8888)      tornado.ioloop.IOLoop.instance().start()

只需要在application中注册url对应的handler即可,对于websocket,只要让handler继承自tornado.websocket.WebSocketHandler。

 

然后用以下代码测试:

<html><head><title>Web Socket Client</title></head>    <body>    <script type="text/javascript">    var socket;    if (!window.WebSocket) {        window.WebSocket = window.MozWebSocket;    }    // Javascript Websocket Client    if (window.WebSocket) {        socket = new WebSocket("ws://localhost:8888/websocket");        socket.onmessage = function(event) {            var ta = document.getElementById('responseText');            ta.value = ta.value + '\n' + event.data        };        socket.onopen = function(event) {            var ta = document.getElementById('responseText');            ta.value = "Web Socket opened!";        };        socket.onclose = function(event) {            var ta = document.getElementById('responseText');            ta.value = ta.value + "Web Socket closed";        };    } else {        alert("Your browser does not support Web Socket.");    }    // Send Websocket data    function send(message) {        if (!window.WebSocket) { return; }        if (socket.readyState == WebSocket.OPEN) {            socket.send(message);        } else {            alert("The socket is not open.");        }    }    </script>    <h3>Send :</h3>    <form onsubmit="return false;">    <input type="text" name="message" value="Hello World!"/><input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)" />    <h3>Receive :</h3>    <textarea id="responseText" style="width:500px;height:300px;"></textarea>    </form>    </body>    </html>  

效果如下:

20130507172443270.jpg