【问题标题】:Asynchronous COMET query with Tornado and PrototypeTornado 和 Prototype 的异步 COMET 查询
【发布时间】:2011-01-20 00:34:23
【问题描述】:

我正在尝试使用 Tornado 和 JS Prototype 库编写简单的 Web 应用程序。因此,客户端可以在服务器上执行长时间运行的作业。我希望这项工作异步运行 - 以便其他客户可以查看页面并在那里做一些事情。

这是我得到的:

#!/usr/bin/env/ python

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)

PS:我看过 Chat 示例,但它太复杂了。无法理解它是如何工作的:(

PSS 下载完整版example

【问题讨论】:

    标签: python ajax comet long-polling tornado


    【解决方案1】:

    Tornado 是单线程网络服务器。 wait_for_smith 方法中的 while 循环正在阻塞 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 才能完成这项工作。

    【讨论】:

    • 我已经尝试过该方法并且可以确认它不再挂起,但现在程序会显示一个警告框,其中未定义 responseText 并且出现 405 错误。
    • 说得太快了,问题出在我头上……我指定了两个不同的地址。这绝对有效。
    • 但是这是长轮询吗?它看起来就像只是对我进行投票。请注意,我自己也是龙卷风/彗星新手。
    【解决方案2】:
    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);
                    }
                })
            }
    

    【讨论】:

    • 在非默认端口的情况下,应该通过整个路径。
    【解决方案3】:

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

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

    您可以阅读introduction here。

    【讨论】:

      【解决方案4】:

      我读过 Ted Roden 的《"Building the Realtime User Experience"》一书,非常有帮助。我已经设法使用 Tornado (python) 创建了一个复杂的实时聊天系统。我推荐这本书和 John Goerzen 的 "Foundations of Python Network Programming" 一起阅读。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-15
        相关资源
        最近更新 更多