tornado 3.2附带的chatdemo的代码中是如何实现异步的?最小利用cpu资源的,我没看见它释放cpu资源。


主程序的代码是:


 #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import logging
import tornado.auth
import tornado.escape
import tornado.ioloop
import tornado.web
import os.path
import uuid

from tornado import gen
from tornado.options import define, options, parse_command_line

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


class MessageBuffer(object):
    def __init__(self):
        self.waiters = set()
        self.cache = []
        self.cache_size = 200

    def wait_for_messages(self, callback, cursor=None):
        if cursor:
            new_count = 0
            for msg in reversed(self.cache):
                if msg["id"] == cursor:
                    break
                new_count += 1
            if new_count:
                callback(self.cache[-new_count:])
                return
        self.waiters.add(callback)

    def cancel_wait(self, callback):
        self.waiters.remove(callback)

    def new_messages(self, messages):
        logging.info("Sending new message to %r listeners", len(self.waiters))
        for callback in self.waiters:
            try:
                callback(messages)
            except:
                logging.error("Error in waiter callback", exc_info=True)
        self.waiters = set()
        self.cache.extend(messages)
        if len(self.cache) > self.cache_size:
            self.cache = self.cache[-self.cache_size:]


# Making this a non-singleton is left as an exercise for the reader.
global_message_buffer = MessageBuffer()


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        user_json = self.get_secure_cookie("chatdemo_user")
        if not user_json: return None
        return tornado.escape.json_decode(user_json)


class MainHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.render("index.html", messages=global_message_buffer.cache)


class MessageNewHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        message = {
            "id": str(uuid.uuid4()),
            "from": self.current_user["first_name"],
            "body": self.get_argument("body"),
        }
        # to_basestring is necessary for Python 3's json encoder,
        # which doesn't accept byte strings.
        message["html"] = tornado.escape.to_basestring(
            self.render_string("message.html", message=message))
        if self.get_argument("next", None):
            self.redirect(self.get_argument("next"))
        else:
            self.write(message)
        global_message_buffer.new_messages([message])


class MessageUpdatesHandler(BaseHandler):
    @tornado.web.authenticated
    @tornado.web.asynchronous
    def post(self):
        cursor = self.get_argument("cursor", None)
        global_message_buffer.wait_for_messages(self.on_new_messages,
                                                cursor=cursor)

    def on_new_messages(self, messages):
        # Closed client connection
        if self.request.connection.stream.closed():
            return
        self.finish(dict(messages=messages))

    def on_connection_close(self):
        global_message_buffer.cancel_wait(self.on_new_messages)


class AuthLoginHandler(BaseHandler, tornado.auth.GoogleMixin):
    @gen.coroutine
    def get(self):
        if self.get_argument("openid.mode", None):
            user = yield self.get_authenticated_user()
            self.set_secure_cookie("chatdemo_user",
                                   tornado.escape.json_encode(user))
            self.redirect("/")
            return
        self.authenticate_redirect(ax_attrs=["name"])


class AuthLogoutHandler(BaseHandler):
    def get(self):
        self.clear_cookie("chatdemo_user")
        self.write("You are now logged out")


def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
            (r"/a/message/new", MessageNewHandler),
            (r"/a/message/updates", MessageUpdatesHandler),
            ],
        cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
        login_url="/auth/login",
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        xsrf_cookies=True,
        )
    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()

主要是class MessageUpdatesHandler(BaseHandler)那里,明明是用了异步的装饰器,但是我没看出来他是如何把他做成异步的,如果没有做成异步的,那这个东西会占用服务器的cpu的资源太多了,我想官方安装包下的demo应该不会出错的,请哪位大神帮我细致的解释一下,这段demo是如何唯美地实现了一个chatroom的功能?(其实它的大致意思我大概是能理解的,就是没发现他是如何在这个问题上用异步的,明明用了异步的装饰器,但是就是没有发现它使如何用异步的)

————————————
注:我理解异步,理解他这个chat的实现思路,只是认为他想做成异步的,但似乎实现异步的过程中是错的,没有用到异步,因为on new message那里虽然用到了异步装饰器,但是没有用到异步。求指出他在具体哪一步释放cpu线程的。对于二楼提出的他构造了一个异步的function的callback,但是callback回调函数不是异步的特有函数,是很平常的函数构造,我没看出他的构造。而我知道把异步的东西分开来构造的是func(args, callback=(yield gen.Callback(key)))
result = yield gen.Wait(key) 虽然说他没有gen,但是他根本没有用到他自己导入的那个tornado.web.asynchronous模块的任何功能。所以说感觉上他就没有实现异步。

其实这个问题的最佳实践方法是websocket,不过我就是觉得除了websocket的另外一个官方的直接不用websocket的代码应该不会有问题,明明用了异步装饰器,但是却没有发现他用到异步的功能。所以疑问。

—————————————
不过可能是我对tornado的理解不够深刻,也许二楼回答的就是对的。先采纳吧。谢谢大家的回答。

异步请求 python python-tornado 异步 tornado

蛋⑨蛋蛋⑨蛋⑨ 10 years, 9 months ago

您可以先看一下 @tornado.web.asynchronous 这个装饰器。根据 docstring 和源码可以得知,由它装饰过的 post() 函数必须自己负责异步地调用 finish()

有了以上知识,我们可以分析一下这个 MessageUpdatesHandler 了,入口是 post() 。第一句:


 cursor = self.get_argument("cursor", None)

是一个简单的阻塞调用,我们并不感兴趣。第二句:


 global_message_buffer.wait_for_messages(self.on_new_messages,
                                                cursor=cursor)

这是比较标准的 Tornado 方式的异步调用——参数里带着一个回调函数(我非 Tornado 长期使用者,结论是根据阅读有限的代码和一些评价得出的)。我们继续跟到这个函数里面去。


 def wait_for_messages(self, callback, cursor=None):
        if cursor:
            new_count = 0
            for msg in reversed(self.cache):
                if msg["id"] == cursor:
                    break
                new_count += 1
            if new_count:
                callback(self.cache[-new_count:])
                return
        self.waiters.add(callback)

这里就是“异步”的关键了。这个方法大部分代码都是在检查这个 buffer 里面有没有足够的数据可以让这次 wait_for_message 直接调用回调函数,如果刚好有数据那就皆大欢喜。

但是如果没有,注意看这个方法将回调函数添加到 self.waiters 队列里之后,就 返回 了。这就意味着, MessageUpdatesHandler.post() 也会立即返回 None ,并且在 Tornado 内部会一直返回到 eventloop ——后者会“释放”CPU,去做循环里的别的事情;而此时这个 HTTP 请求,并没有因为函数的返回而结束,因为还没有人调用 finish() ——回忆一下 @asynchronous

此时异步地(在 eventloop 转了许多圈之后), MessageBuffer.new_messages() 会被调用到(就不细分析了),然后会调用到之前放在 waiters 队列里的回调函数——也就是 MessageUpdatesHandler.on_new_messages


 def on_new_messages(self, messages):
        # Closed client connection
        if self.request.connection.stream.closed():
            return
        self.finish(dict(messages=messages))

它调用了 finish() ,至此请求完成。

阿尔萨斯之流 answered 10 years, 9 months ago

Your Answer