基于Tornado和prototype的异步COMET查询

2024-05-02 17:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Tornado和JS原型库编写简单的web应用程序。因此,客户端可以在服务器上执行长时间运行的作业。我希望,这个作业可以异步运行,这样其他客户机就可以查看页面并在那里执行一些操作。

我得到的是:

#!/usr/bin/env/ pytthon

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options

import os
import string
from time import sleep
from datetime import datetime

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

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("templates/index.html", title="::Log watcher::", c_time=datetime.now())

class LongHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.wait_for_smth(callback=self.async_callback(self.on_finish))
        print("Exiting from async.")
        return

    def wait_for_smth(self, callback):
        t=0
        while (t < 10):
            print "Sleeping 2 second, t={0}".format(t)
            sleep(2)
            t += 1
        callback()

    def on_finish(self):
        print ("inside finish")
        self.write("Long running job complete")
        self.finish()



def main():
    tornado.options.parse_command_line()

    settings = {
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        }

    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/longPolling", LongHandler)
        ], **settings
    )
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()

这是服务器部分。它有一个主视图(显示很少的问候语、当前服务器时间和ajax查询的url),用于执行长时间运行的作业。如果按下按钮,将执行长时间运行的作业。服务器挂起:(此作业正在运行时,我无法查看任何页面。 以下是模板页:

<html>
<head>
    <title>{{ title }}</title>

    <script type="text/javascript" language="JavaScript" src="{{ static_url("js/prototype.js")}}"></script>


    <script type='text/javascript' language='JavaScript'>
        offset=0
        last_read=0

        function test(){
            new Ajax.Request("http://172.22.22.22:8888/longPolling",
            {
                method:"get",
                asynchronous:true,
                onSuccess: function (transport){
                    alert(transport.responseText);
                }
            })
        }


    </script>
</head>
<body>
    Current time is {{c_time}}
    <br>
    <input type="button" value="Test" onclick="test();"/>
</body>
</html>

我做错什么了?如何使用Tornado和Prototype(或jQuery)实现长池

我看过聊天的例子,但太复杂了。无法理解它是如何工作的:

PSS完全下载example


Tags: fromimportself服务器webtimetitledef
3条回答
function test(){
            new Ajax.Request("http://172.22.22.22:8888/longPolling",
            {
                method:"get",
                asynchronous:true,
                onSuccess: function (transport){
                    alert(transport.responseText);
                }
            })
        }

应该是

function test(){
            new Ajax.Request("/longPolling",
            {
                method:"get",
                asynchronous:true,
                onSuccess: function (transport){
                    alert(transport.responseText);
                }
            })
        }

Tornado是单线程web服务器。你的while循环在wait_for_smith方法中阻塞了Tornado。

您可以这样重写该方法:

def wait_for_smth(self, callback, t=10):
    if t:
        print "Sleeping 2 second, t=%s" % t
        tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 2, lambda: self.wait_for_smth(callback, t-1))
    else:
        callback()

您需要在顶部添加import time才能使其工作。

我已经将Tornado的聊天示例转换为在gevent上运行。看看the live demo herethe explanation and source code here

它使用轻量级用户级线程(greenlets),在速度/内存使用方面与Tornado相当。但是,代码很简单,您可以在处理程序中调用sleep()和urlopen(),而不阻塞整个过程,并且可以生成执行相同操作的长时间运行的作业。在幕后,应用程序是异步的,由一个用C(libevent)编写的事件循环提供动力。

你可以阅读introduction here

相关问题 更多 >