python - 使用 Tornado 和 Prototype 的异步 COMET 查询

标签 python ajax comet long-polling tornado

我正在尝试使用 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 下载完整 example

最佳答案

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 才能使其正常工作。

关于python - 使用 Tornado 和 Prototype 的异步 COMET 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317501/

相关文章:

c# - 是否有像 Tornado 这样的基于 C# 的开源非阻塞、基于事件的 Web 服务器?

python - 比较 2 个句子并拆分为数据框

python - 从文本文件加载keras模型

python - 通过多个循环合并 Excel 工作表

python - Pandas 插值按组添加行,每组具有不同的范围

javascript - HTTP_ORIGIN header 未通过 jquery ajax 发送

javascript - 服务器的安全 ajax GET/POST 请求

javascript - Bootstrap 弹出窗口加载

java - 无法使用 easteasy 获得异步响应

java - 安卓 : Keep httpclient running in background and communicate with activity when message recieved by httpclient