Tornado:我可以在异步 RequestHandler 中调用 self.finish() 后运行代码吗? [英] Tornado: Can I run code after calling self.finish() in an asynchronous RequestHandler?

查看:23
本文介绍了Tornado:我可以在异步 RequestHandler 中调用 self.finish() 后运行代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Tornado.我有一堆异步请求处理程序.他们中的大多数都是异步完成工作的,然后将工作结果报告给用户.但是我有一个处理程序,它的工作是简单地告诉用户他们的请求将在未来的某个时候得到处理.我完成了 HTTP 连接,然后做更多的工作.这是一个简单的例子:

I'm using Tornado. I have a bunch of asynchronous request handlers. Most of them do their work asynchronously, and then report the result of that work back to the user. But I have one handler whose job it is to simply tell the user that their request is going to be processed at some point in the future. I finish the HTTP connection and then do more work. Here's a trivialized example:

class AsyncHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self, *args, **kwargs):
        # first just tell the user to go away
        self.write("Your request is being processed.")
        self.finish()

        # now do work
        ...

我的问题是:这是对 Tornado 的合法使用吗?self.finish() 之后的代码会可靠运行吗?我以前从未遇到过它的问题,但现在我在我的一个开发环境(不是全部)中看到了它的问题.这里有许多我已经确定的变通方法,但我想确保我没有遗漏 Tornado 中请求生命周期的基本内容.似乎没有理由在调用 self.finish() 后我无法运行代码,但也许我错了.

My question is: is this a legitimate use of Tornado? Will the code after the self.finish() run reliably? I've never had a problem with it before, but now I'm seeing a problem with it in one of my development environments (not all of them). There are a number of work-arounds here that I've already identified, but I want to make sure I'm not missing something fundamental to the request-lifecycle in Tornado. There doesn't SEEM to be a reason why I wouldn't be able to run code after calling self.finish(), but maybe I'm wrong.

谢谢!

推荐答案

是的,你可以.

您必须定义 RequestHandleron_finish 方法.这是在请求完成并将响应发送给客户端后运行的函数.

You have to define on_finish method of your RequestHandler. This is a function run after the request finished and has sent the response to client.

RequestHandler.on_finish()

在请求结束后调用.

覆盖此方法以执行清理、日志记录等.此方法是对方准备.on_finish 可能不会产生任何输出,因为它在响应发送到客户端后调用.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

这篇关于Tornado:我可以在异步 RequestHandler 中调用 self.finish() 后运行代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆