9

我正在尝试使用 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 example,但它太复杂了。无法理解它是如何工作的:(

PSS 下载完整示例

4

4 回答 4

15

Tornado 是单线程网络服务器。您的 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在顶部添加才能使这项工作。

于 2010-03-12T05:05:43.863 回答
1
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);
                }
            })
        }
于 2011-06-26T13:34:29.303 回答
0

I have read the book called "Building the Realtime User Experience" by Ted Roden, and it was very helpful. I have managed to create a complex realtime chat system using Tornado (python). I recommend this book to be read as well as "Foundations of Python Network Programming" by John Goerzen.

于 2012-02-25T13:50:44.887 回答
0

我已将 Tornado 的聊天示例转换为在gevent上运行。看看这里的现场演示和这里解释和源代码

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

你可以在这里阅读介绍

于 2010-08-03T16:26:28.540 回答