Rust天气API集成库weer_api的使用,高效获取和解析天气数据的Rust插件库
Weer API
一个用于使用Weather API的封装库
这是一个非官方库
使用方法
在您的Cargo.toml中添加以下内容:
[dependencies]
weer_api = "0.1.0"
示例
获取天气预报
use weer_api::{*, chrono::{Utc, TimeZone}};
let client = Client::new("api_key", true);
let result = client.forecast()
.query(Query::City("London".to_string()))
.dt(Utc.ymd(2022, 08, 21).and_hms(0, 0, 0))
.lang(Language::Spanish)
.call();
assert!(result.is_ok())
获取未来天气
use weer_api::{*, chrono::{Utc, TimeZone}};
let client = Client::new("api_key", true);
let result = client.future()
.query(Query::Coords(48.8567, 2.3508))
.dt(Utc.ymd(2022, 09, 21).and_hms(0, 0, 0))
.lang(Language::Spanish)
.call();
assert!(result.is_ok())
获取历史天气
use weer_api::{*, chrono::{Utc, TimeZone}};
let client = Client::new("api_key", true);
let result = client.history()
.query(Query::Ip(None))
.dt(Utc.ymd(2022, 07, 21).and_hms(0, 0, 0))
.hour()
.call();
assert!(result.is_ok())
完整示例代码
下面是一个更完整的示例,展示如何使用weer_api库获取当前天气、未来天气和历史天气数据:
use weer_api::{*, chrono::{Utc, TimeZone}};
fn main() {
// 替换为您的API密钥
let api_key = "your_api_key_here";
// 创建客户端实例
let client = Client::new(api_key, true);
// 示例1: 获取当前天气预报
let current_forecast = client.forecast()
.query(Query::City("London".to_string()))
.lang(Language::English)
.call();
match current_forecast {
Ok(data) => {
println!("=== 当前天气 ===");
println!("城市: London");
println!("温度: {}°C", data.current.temp_c);
println!("天气状况: {}", data.current.condition.text);
println!("风速: {} kph", data.current.wind_kph);
println!("湿度: {}%", data.current.humidity);
}
Err(e) => eprintln!("获取当前天气失败: {}", e),
}
// 示例2: 获取未来天气
let future_weather = client.future()
.query(Query::Coords(48.8567, 2.3508)) // 巴黎坐标
.dt(Utc.ymd(2023, 12, 25).and_hms(0, 0, 0)) // 圣诞节日期
.lang(Language::French)
.call();
match future_weather {
Ok(data) => {
println!("\n=== 未来天气 ===");
println!("位置: 巴黎 (48.8567, 2.3508)");
println!("日期: 2023-12-25");
println!("预测温度: {}°C", data.forecast.forecastday[0].day.avgtemp_c);
}
Err(e) => eprintln!("获取未来天气失败: {}", e),
}
// 示例3: 获取历史天气
let history_weather = client.history()
.query(Query::Ip(None)) // 使用当前IP地址
.dt(Utc.ymd(2022, 7, 21).and_hms(0, 0, 0))
.hour() // 获取小时级数据
.call();
match history_weather {
Ok(data) => {
println!("\n=== 历史天气 ===");
println!("日期: 2022-07-21");
if let Some(hour) = data.forecast.forecastday[0].hour.first() {
println!("午夜温度: {}°C", hour.temp_c);
}
}
Err(e) => eprintln!("获取历史天气失败: {}", e),
}
}
许可证
- MIT
1 回复
以下是基于提供内容的完整示例demo,我将先展示内容中的示例,然后提供更完整的实现:
内容中提供的示例代码:
// 示例1: 初始化客户端
use weer_api::Client;
#[tokio::main]
async fn main() {
let api_key = "your_api_key_here";
let client = Client::new(api_key);
}
// 示例2: 获取当前天气
let weather = client.current_weather("London").await.unwrap();
println!("当前温度: {}°C", weather.main.temp);
println!("天气状况: {}", weather.weather[0].description);
// 示例3: 获取天气预报
let forecast = client.forecast("New York", 5).await.unwrap();
for day in forecast.list {
println!("日期: {}", day.dt_txt);
println!("最高温度: {}°C", day.main.temp_max);
println!("最低温度: {}°C", day.main.temp_min);
}
完整示例demo:
use weer_api::{Client, params::{CurrentWeatherParams, Units, ForecastParams}};
use std::{io, time::Duration};
use tokio::time;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 初始化客户端
let api_key = "your_api_key_here"; // 替换为实际API密钥
let client = Client::new(api_key);
// 用户输入城市名称
println!("请输入要查询的城市名称:");
let mut city = String::new();
io::stdin().read_line(&mut city)?;
let city = city.trim();
// 配置当前天气查询参数
let current_params = CurrentWeatherParams {
city: city.to_string(),
units: Some(Units::Metric), // 使用公制单位
lang: Some("zh_cn".to_string()), // 中文描述
..Default::default()
};
// 配置天气预报参数
let forecast_params = ForecastParams {
city: city.to_string(),
days: 3, // 获取3天预报
units: Some(Units::Metric),
..Default::default()
};
// 获取当前天气
match client.current_weather_with_params(current_params).await {
Ok(weather) => {
println!("\n=== {} 当前天气 ===", weather.name);
println!("温度: {:.1}°C", weather.main.temp);
println!("体感温度: {:.1}°C", weather.main.feels_like);
println!("湿度: {}%", weather.main.humidity);
println!("气压: {} hPa", weather.main.pressure);
println!("天气: {}", weather.weather[0].description);
println!("风速: {:.1} m/s", weather.wind.speed);
println!("能见度: {} 米", weather.visibility);
},
Err(e) => eprintln!("获取当前天气失败: {}", e),
}
// 添加延迟防止API速率限制
time::sleep(Duration::from_secs(1)).await;
// 获取天气预报
match client.forecast_with_params(forecast_params).await {
Ok(forecast) => {
println!("\n=== {} 天气预报 ===", forecast.city.name);
for day in forecast.list {
println!("\n日期: {}", day.dt_txt);
println!("天气: {}", day.weather[0].description);
println!("温度: {:.1}°C (最高: {:.1}°C, 最低: {:.1}°C)",
day.main.temp, day.main.temp_max, day.main.temp_min);
println!("降水概率: {}%", day.pop.unwrap_or(0.0) * 100.0);
}
},
Err(e) => eprintln!("获取天气预报失败: {}", e),
}
Ok(())
}
这个完整示例展示了:
- 同时使用当前天气和天气预报功能
- 更全面的参数配置
- 更详细的天气信息输出
- 基本的错误处理和API调用间隔
- 中文化天气描述
- 用户交互输入
注意使用时需要:
- 替换为有效的API密钥
- 根据实际需求调整查询参数
- 考虑添加更完善的错误处理和重试逻辑