Tornado 协程:Return 值和一次执行
Tornado Coroutine : Return value and one time execution
我是 Tornado 的新手,所以我想知道下面的代码是解决问题的正确方法还是有更好的方法。它有效,但我不确定它的效率。
代码基于文档here
在我的脚本中间,我需要 运行 HTTP 请求 (10-50)。显然,可以通过这种方式并行执行此操作:
@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
# responses is a list of HTTPResponses in the same order
协程完成后如何访问响应?我可以只添加 return responses
吗?
另外,因为我只需要在我的代码中使用一次异步进程,所以我以这种方式启动 IOLoop :
# run_sync() doesn't take arguments, so we must wrap the
# call in a lambda.
IOLoop.current().run_sync(lambda: parallel_fetch_many(googleLinks))
这样做对吗?或者我应该只在脚本开头启动 IOLoop 并在结尾停止它,即使我只使用一次异步进程。
基本上,我的问题是:下面的代码是否正确?
@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
return responses
googleLinks = [url1,url2,...,urln]
responses = IOLoop.current().run_sync(lambda:parallel_fetch_many(googleLinks))
do_something(responses)
是的,我认为你的代码是正确的。
我是 Tornado 的新手,所以我想知道下面的代码是解决问题的正确方法还是有更好的方法。它有效,但我不确定它的效率。
代码基于文档here
在我的脚本中间,我需要 运行 HTTP 请求 (10-50)。显然,可以通过这种方式并行执行此操作:
@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
# responses is a list of HTTPResponses in the same order
协程完成后如何访问响应?我可以只添加 return responses
吗?
另外,因为我只需要在我的代码中使用一次异步进程,所以我以这种方式启动 IOLoop :
# run_sync() doesn't take arguments, so we must wrap the
# call in a lambda.
IOLoop.current().run_sync(lambda: parallel_fetch_many(googleLinks))
这样做对吗?或者我应该只在脚本开头启动 IOLoop 并在结尾停止它,即使我只使用一次异步进程。
基本上,我的问题是:下面的代码是否正确?
@gen.coroutine
def parallel_fetch_many(urls):
responses = yield [http_client.fetch(url) for url in urls]
return responses
googleLinks = [url1,url2,...,urln]
responses = IOLoop.current().run_sync(lambda:parallel_fetch_many(googleLinks))
do_something(responses)
是的,我认为你的代码是正确的。