Tornado处理程序在python中分配额外的工作

时间:2015-07-29 20:29:48

标签: python rest python-3.x tornado

我有一个通过龙卷风暴露的简单API。以前,其中一个查询导致rsync运行。通过试验,错误,探索,我发现我可以解雇它,以免它阻止及时响应:

tornado.process.Subprocess(['rsync', '-vazh', ... ])

我现在正在改进此代码,以便它不再运行外部rsync,而是推送另一项服务。我正在使用请求:

requests.post('http://other.service/foo/bar)

此服务背后的网络具有非常高的延迟(对于rysnc进程也是如此),所以我仍然希望将其分解,以便我不会及时推迟响应。 tornado.process.Subprocess似乎非常适合调用非python shell程序来完成工作。对于像上面这样的python代码是否有相同的效果?

1 个答案:

答案 0 :(得分:2)

tornado有一个内置的HTTP客户端,您可以使用它代替requeststornado.httpclient

from tornado.httpclient import AsyncHTTPClient

def handle_request(response):
    if response.error:
        print "Error:", response.error
    else:
        print response.body

http_client = AsyncHTTPClient()
http_client.fetch("http://other.service/foo/bar", method='POST', callback=handle_request)

如果你想要它也可以用作协程:

@coroutine
def some_method(self):
    http_client = AsyncHTTPClient()
    repsonse = yield http_client.fetch("http://other.service/foo/bar", method='POST')
   if response.error:
       print "Error:", response.error
   else:
       print response.body

如果您正在运行任意阻止Python代码(意味着您无法轻易找到非阻塞,龙卷风兼容的替代品),您应该咨询this question,了解如何使用{{{{}进行多处理1}}。简短的回答是,在Python 3.x上,您可能希望使用tornado来运行阻止代码,因为当您{concurrent.futures.ProcessPoolExecutor concurrent.futures.Future将与tornado事件循环正确集成时1}}来自一个。