在 python 中分叉额外工作的 Tornado 处理程序
Tornado handler that forks additional work in python
我有一个简单的 API 通过龙卷风暴露。以前,其中一个查询导致 rsync
到 运行。通过试验、错误、探索,我发现我可以将其 fork 掉,这样它就不会阻止及时响应:
tornado.process.Subprocess(['rsync', '-vazh', ... ])
我现在正在改进此代码,以便它不再 运行 是外部 rsync
,而是戳另一项服务。我正在使用 Requests 这样做:
requests.post('http://other.service/foo/bar)
此服务背后的网络延迟非常高(rysnc 进程也是如此),所以我仍然希望将其分叉出来,这样我就不会推迟及时响应。 tornado.process.Subprocess
似乎很适合调用非 python shell 程序来完成工作。对于上面的 python 代码,是否有等效的方法?
tornado
有一个内置的 HTTP 客户端,您可以使用它来代替 requests
:tornado.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,关于在 tornado
中使用多处理。简短的回答是,在 Python 3.x 你可能想使用 concurrent.futures.ProcessPoolExecutor
到 运行 阻塞代码,因为 concurrent.futures.Future
将与 tornado
事件循环,当你 yield
从一个。
我有一个简单的 API 通过龙卷风暴露。以前,其中一个查询导致 rsync
到 运行。通过试验、错误、探索,我发现我可以将其 fork 掉,这样它就不会阻止及时响应:
tornado.process.Subprocess(['rsync', '-vazh', ... ])
我现在正在改进此代码,以便它不再 运行 是外部 rsync
,而是戳另一项服务。我正在使用 Requests 这样做:
requests.post('http://other.service/foo/bar)
此服务背后的网络延迟非常高(rysnc 进程也是如此),所以我仍然希望将其分叉出来,这样我就不会推迟及时响应。 tornado.process.Subprocess
似乎很适合调用非 python shell 程序来完成工作。对于上面的 python 代码,是否有等效的方法?
tornado
有一个内置的 HTTP 客户端,您可以使用它来代替 requests
:tornado.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,关于在 tornado
中使用多处理。简短的回答是,在 Python 3.x 你可能想使用 concurrent.futures.ProcessPoolExecutor
到 运行 阻塞代码,因为 concurrent.futures.Future
将与 tornado
事件循环,当你 yield
从一个。