修改了weather-test的位置,并尝试做插入数据库

This commit is contained in:
2025-09-22 17:02:30 +08:00
parent 40d4c9ad49
commit b294b6cc90

View File

@@ -101,24 +101,6 @@ pub struct WeatherData {
wind_speed_suitability: String, wind_speed_suitability: String,
} }
#[post("/weather-test")]
async fn post_weather_data(data: web::Json<WeatherData>) -> impl Responder {
// 在这里处理接收到的数据
println!("Received weather data: {:#?}", data);
// 示例:访问特定字段
println!("Area Type: {}", data.area_type);
println!("Wind Speeds: {:?}", data.wind_speed);
println!("Location: ({}, {})", data.latitude, data.longitude);
// 返回成功响应
web::Json(serde_json::json!({
"status": "success",
"message": "Weather data received successfully",
"received_assignment": data.assignment_number
}))
}
// 定义请求体结构 // 定义请求体结构
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct OpenIdRequest { struct OpenIdRequest {
@@ -308,6 +290,134 @@ async fn get_openid(
HttpResponse::Ok().json(OpenIdResponse { openid }) HttpResponse::Ok().json(OpenIdResponse { openid })
} }
#[post("/weather-test")]
async fn post_weather_data(
data: web::Json<WeatherData>,
pool: web::Data<PgPool>,
) -> impl Responder {
// 打印接收的数据
println!("Received weather data: {:#?}", data);
// 1. 根据openid查询user_id
let openid = &data.openid;
let query_user = r#"
SELECT id FROM users WHERE openid = $1
"#;
let user_id_result: Result<Option<(i32,)>, sqlx::Error> =
sqlx::query_as::<_, (i32,)>(query_user)
.bind(openid)
.fetch_optional(pool.get_ref())
.await;
let user_id = match user_id_result {
Ok(Some((id,))) => id,
Ok(None) => {
let error_msg = format!("未找到openid为 {} 的用户", openid);
eprintln!("{}", error_msg);
// 返回200状态码但success为false
return HttpResponse::Ok().json(serde_json::json!({
"success": false,
"errcode": 404,
"errmsg": error_msg
}));
}
Err(e) => {
let error_msg = format!("查询用户失败: {}", e);
eprintln!("{}", error_msg);
return HttpResponse::Ok().json(serde_json::json!({
"success": false,
"errcode": 500,
"errmsg": error_msg
}));
}
};
// 2. 将天气数据插入数据库
let insert_query = r#"
INSERT INTO weather_data (
user_id, title, date, hour, min, longitude, latitude, daysincejanfirst,
theta, solardeclination, sunaltitude, overallcloudiness, lowcloudiness,
cloudindex, solarradiationlevel, hasmeasuredwindspeed, measuredwindspeed,
convertedwindspeed, measurementheight, areatype, pointwindspeed,
atmosphericstability, suitabilitydegree, winddirection, averagewinddirection,
winddirectionstandarddeviation, windspeed, averagewindspeed, windspeedsuitability,
winddirectionsuitability, overallsuitability, inspectiontype, assignmentnumber,
calculatedwindspeed
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19,
$20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34
) RETURNING id
"#;
// 转换经纬度为字符串
let longitude_str = data.longitude.to_string();
let latitude_str = data.latitude.to_string();
// 执行插入操作
let result = sqlx::query_as::<_, (i32,)>(insert_query)
.bind(user_id)
.bind(&data.title)
.bind(&data.date)
.bind(data.hours)
.bind(data.min)
.bind(&longitude_str)
.bind(&latitude_str)
.bind(data.day_since_jan_first)
.bind(data.theta)
.bind(data.solar_declination)
.bind(data.sun_altitude)
.bind(&data.overall_cloudiness)
.bind(&data.low_cloudiness)
.bind(&data.cloud_index)
.bind(data.solar_radiation_level as i32)
.bind(data.has_measured_wind_speed)
.bind(data.measured_wind_speed)
.bind(data.converted_wind_speed as i32)
.bind(data.measurement_height)
.bind(&data.area_type)
.bind(data.point_wind_speed)
.bind(&data.atmospheric_stability)
.bind(&data.suitability_degree)
.bind(serde_json::to_value(&data.wind_direction).unwrap())
.bind(data.average_wind_direction)
.bind(data.wind_direction_standard_deviation)
.bind(serde_json::to_value(&data.wind_speed).unwrap())
.bind(data.average_wind_speed)
.bind(&data.wind_speed_suitability)
.bind(&data.wind_direction_suitability)
.bind(&data.overall_suitability)
.bind(&data.inspection_type)
.bind(&data.assignment_number)
.bind(data.calculated_wind_speed)
.fetch_one(pool.get_ref())
.await;
match result {
Ok((inserted_id,)) => {
println!(
"Successfully inserted weather data with id: {}",
inserted_id
);
HttpResponse::Ok().json(serde_json::json!({
"success": true, // 前端期望的成功标识
"message": "Weather data inserted successfully",
"inserted_id": inserted_id,
"received_assignment": data.assignment_number
}))
}
Err(e) => {
let error_msg = format!("插入数据失败: {}", e);
eprintln!("{}", error_msg);
HttpResponse::Ok().json(serde_json::json!({
"success": false, // 前端期望的失败标识
"errcode": 500,
"errmsg": error_msg
}))
}
}
}
// 创建服务器配置的函数 // 创建服务器配置的函数
fn create_server_config( fn create_server_config(
pool: PgPool, pool: PgPool,