Lingara Lingara 文档 学习指南 API 库 应用 构建 网页版
语言: 中文简体

Rust

本页译自英文。如两者有出入,以英文页面为准。 阅读英文页面

Rust 库是 crates.io 上的 lingara crate。它需要 Rust 1.87 或更高版本,运行在 Tokio 运行时上。TLS 默认由 rustls 提供,也可以通过一个 feature 改用平台自带的 TLS。

用法一览

  • 每个调用都是一个 async fn,返回 Result。要取消调用,就丢弃它的 future;要取消流,就丢弃该流。
  • 响应头一到,流就随之到达,形式是由结果组成的 Stream。用 .next().await 读取它。
  • 错误是一个带有四个变体的 Error 枚举。如果 API 指定了等待时间,Error::retry_after 会返回它。
  • 用 Client::builder() 构建客户端。要共享连接池,可以传入你自己的 reqwest::Client,但不要给该客户端设置总超时,否则它会把长时间的流提前截断。要给单个调用设定截止时间,就用 tokio::time::timeout 包裹它。

下面的示例会安装 crate、创建客户端、以流的方式获取词汇列表并处理错误。

Rust

cargo add lingara@0.1.0-alpha.6
cargo add tokio --features macros,rt-multi-thread

Rust

use lingara::Client;

let client = Client::builder()
    .client_credentials(std::env::var("LINGARA_CLIENT_ID")?, std::env::var("LINGARA_CLIENT_SECRET")?)
    .build()?;

Rust

use lingara::models::{GenerateVocabularyEvent, VocabRequest};
use std::num::NonZeroU8;

let request = VocabRequest { level: 2, source_lang: "en".into(), target_lang: "zh".into(), count: NonZeroU8::new(8) };
let mut stream = client.generate_vocabulary(&request).await?;
while let Some(event) = stream.next().await {
    if let GenerateVocabularyEvent::Item(item) = event? {
        println!("{} {}", item.word, item.translation);
    }
}

Rust

use lingara::Error;

let result = client.get_usage().await;
if let Some(wait) = result.as_ref().err().and_then(Error::retry_after) {
    eprintln!("the API asks you to retry after {wait:?}");
}
match result {
    Ok(usage) => println!("{} allowance rows", usage.allowance.len()),
    // A refusal from the API: status, code (stable) and message (localised).
    Err(Error::Api(e)) => eprintln!("{} {} {}", e.status, e.code, e.message),
    // The token endpoint refused the credentials or the scopes.
    Err(Error::OAuth(e)) => eprintln!("{} {} {}", e.status, e.error, e.description.unwrap_or_default()),
    Err(Error::Maintenance(_)) => eprintln!("the API is under maintenance"),
    // No usable answer: connect, tls, reset, timeout, and so on.
    Err(Error::Transport(e)) => eprintln!("transport: {}", e.kind),
    Err(other) => return Err(other.into()),
}

本页封装的内容