在写入客户端之前链接异步操作(python - 龙卷风) [英] chaining asynchronous operations before writing to client (python - tornado)

查看:23
本文介绍了在写入客户端之前链接异步操作(python - 龙卷风)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个简单的异步情况下,处理程序可能如下所示:

In a simple async case, handler might look like:

@tornado.web.authenticated
@tornado.web.asynchronous
def post(self):
    AsyncHTTPClient().fetch("http://api.example.com/", self.on_post_response)

def on_post_response(self, response):
    self.render("template.html", status=response.error)

然而,在返回客户端之前,我需要执行两个异步操作(获取远程rest api,然后发送带有结果的邮件).

However, I have come to a point when I need to perform two async operations (fetching remote rest api, and then sending mail with the results) before returning to the client.

我想知道是否有一种内置"的方式来做到这一点,例如通过向队列添加回调(如 ioloop.add_callback),或者我是否必须编写一个自定义对象来管理这些任务及其状态并从 post 调用它.

I wonder if there is a "buit-in" way to do this, e.g. by adding callbacks to a queue (like ioloop.add_callback) or do I have to compose a custom object which will manage those tasks and their state and call it from post.

推荐答案

您是否考虑过以下方法?

Have you considered the following approach?

@tornado.web.authenticated
@tornado.web.asynchronous
def post(self):
    async_fetch(..., self._on_fetch_response)

def _on_fetch_response(self, response):
    async_mail(response, self._on_mail_response)

def _on_mail_response(self, response):
    self.render(...) # render() automatically calls self.finish()

或者使用 tornado.gen:

@asynchronous
@gen.engine
def post(self):
    fetch_response = yield gen.Task(async_fetch, ...)
    mail_response = yield gen.Task(async_mail, ...)
    self.render(...)

这篇关于在写入客户端之前链接异步操作(python - 龙卷风)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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