5个版本 (3个重大更改)
0.4.0 | 2024年5月31日 |
---|---|
0.3.0 | 2024年3月27日 |
0.2.0 | 2023年4月25日 |
0.1.1 | 2022年10月28日 |
0.1.0 | 2022年10月7日 |
#398 in Web编程
每月344次下载
用于openweathermap_exporter
32KB
564 行
OpenWeatherMap客户端
openweathermap_client
是一个Rust库,提供查询OpenWeatherMap免费2.5版本天气API的客户端。|
特性
- 使用
serde
将查询结果绑定到从OpenWeatherMap天气数据文档派生出的结构体中。 - 支持以OWM的
Standard
、Metric
或Imperial
单位系统请求结果。 - 支持将城市名称和天气描述翻译成支持的语言。
- 跨平台。已测试,确认在Windows、MacOS、Linux以及许多硬件架构上运行(即将推出)。
- 使用
hyper
通过https
进行查询(某些现有的导出器不使用)。- 不需要安装openssl,因为它使用
hyper_rustls
,因此可以在奇怪的架构上使用。
- 不需要安装openssl,因为它使用
- 无panic。
用法
获取API密钥
要获取OpenWeatherMap API密钥,请参阅本节。
将客户端添加到您的项目中
cargo add openweathermap_client
示例1
获取巴黎现在的温度(°C)和天气描述。
use openweathermap_client::models::{City, UnitSystem};
use openweathermap_client::{error::ClientError, Client, ClientOptions};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), ClientError> {
let options = ClientOptions {
units: UnitSystem::Metric,
language: "fr".to_string(),
..ClientOptions::default() // loads API_KEY env var
};
let client = Client::new(options)?;
let reading = client.fetch_weather(&City::new("Paris", "FR")).await?;
println!(
"The temperature and weather in France in French is {}, {}",
reading.main.temp, reading.weather[0].description
);
Ok(())
}
示例2
重用客户端以获取不同位置和不同查询类型的读取值。
use openweathermap_client::models::{City, CityId, Coord};
use openweathermap_client::{error::ClientError, Client, ClientOptions, Query};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), ClientError> {
// reuse a client for several readings (must be run in an async context)
let client = Client::new(ClientOptions::default())?; // loads API_KEY env var
let v: Vec<Box<dyn Query>> = vec![
Box::new(City::new("Lages", "BR")),
Box::new(CityId::new(3369157)),
Box::new(Coord::new(61.1595054, -45.4409551)),
];
for query in v {
let weather = client.fetch_weather(query.as_ref()).await?;
println!("The weather for {} is {:?}", query, weather);
}
Ok(())
}
相关Crate
请参阅openweathermap_exporter,这是一个允许收集多个位置的天气数据并通过发布读取值以Prometheus导出格式与指标聚合器共享的服务。
依赖
~15–25MB
~482K SLoC