Tornado 6.5 Documentation
httpclient import HTTPClient def synchronous_fetch(url): http_client = HTTPClient() response = http_client.fetch(url) return response.body And here is the same function rewritten asynchronously as a native coroutine: AsyncHTTPClient async def asynchronous_fetch(url): http_client = AsyncHTTPClient() response = await http_client.fetch(url) return response.body Or for compatibility with older versions of Python, using the tornado coroutine def async_fetch_gen(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) raise gen.Return(response.body) Coroutines are a little magical, but what they do internally0 码力 | 272 页 | 1.12 MB | 2 月前3Tornado 6.5 Documentation
HTTPClient def synchronous_fetch(url): http_client = HTTPClient() response = http_client.fetch(url) return response.body And here is the same function rewritten asynchronously as a native def asynchronous_fetch(url): http_client = AsyncHTTPClient() response = await http_client.fetch(url) return response.body Or for compatibility with older versions of Python, using the tornado def async_fetch_gen(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) raise gen.Return(response.body) Coroutines are a little magical, but what they do internally0 码力 | 437 页 | 405.14 KB | 2 月前3Rust 程序设计语言 简体中文版 1.85.0
page_title(url: &str) -> Option{ let response = trpl::get(url).await; let response_text = response.text().await; Html::parse(&response_text) .select_first("title") .map(|title_element| thread::spawn 的行为,当时传递给另一个线程的闭包会 立即开始运行。它也不同于许多其他语言实现 async 的方式。但这样做对于 Rust 提 供与迭代器相同级别的性能保证至关重要。 当我们有了 response_text 字符串后,就可以使用 Html::parse 将其解析为一个 Html 类型的 实例。不同于原始字符串,现在我们有了一个可以将 HTML 作为更丰富数据结构来操作的数 据类型。特别是我们可以使用 修改 page_title 的函数体来链式调用 trpl::get 和 text 并在其之间使用 await,如示例 17-2 所 示: 文件名:src/main.rs let response_text = trpl::get(url).await.text().await; 这样我们就成功编写了第一个异步函数!在我们向 main 加入一些代码调用它之前,让我们再 多了解下我们写了什么以及它的意义。 0 码力 | 562 页 | 3.23 MB | 10 天前3
共 3 条
- 1