Lingara Lingara Dokumentasie Gidse API Biblioteke Apps Bou Webtoepassing
Taal: Afrikaans

Rust

Hierdie bladsy is uit Engels vertaal. As die twee verskil, is die Engelse bladsy korrek. Lees die Engelse bladsy

Die Rust-biblioteek is die lingara-crate op crates.io. Dit vereis Rust 1.87 of later en loop op die Tokio-looptyd. TLS kom by verstek van rustls, of via ‘n feature van die platform se eie TLS.

Hoe dit lees

  • Elke oproep is ‘n async fn wat ‘n Result teruggee. Om ‘n oproep te kanselleer, laat val sy future; om ‘n stroom te kanselleer, laat val die stroom.
  • ‘n Stroom kom aan sodra die antwoordkopskrifte aankom, as ‘n Stream van resultate. Lees dit met .next().await.
  • Foute is een Error-enum met vier variante. Error::retry_after gee die wagtyd terug wat die API genoem het, as daar een was.
  • Bou ‘n kliënt met Client::builder(). Om ‘n verbindingspoel te deel, gee dit jou eie reqwest::Client, maar gee daardie kliënt geen totale uitteltyd nie, anders sal dit lang strome voortydig afsny. Vir ‘n sperdatum op een oproep, draai dit in tokio::time::timeout toe.

Die voorbeelde hieronder installeer die crate, skep ‘n kliënt, stroom ‘n woordelys en hanteer ‘n fout.

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()),
}

Wat hierdie bladsy omvou