如何反序列化actix web表单数据,并将其序列化为csv文件?

sy5wg1nm  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(110)

如何反序列化actix_web表单数据并将其序列化为csv文件?是否可以使用一个结构体?如何覆盖csv错误场景?在我的第一个Rust程序中,我试图将表单数据x-www-form-urlencoded保存到csv文件中,但这种语言与Ruby相比过于严格;)如何将负责保存到csv的代码移动到专用函数?

extern crate csv;
#[macro_use]
extern crate serde_derive;
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
use std::io;

#[derive(Serialize, Deserialize)]
struct FormData {
    email: String,
    fullname: String,
    message: String,
}

async fn contact(form: web::Form<FormData>) -> Result<String> {
    let mut wtr = csv::Writer::from_writer(io::stdout());
    wtr.serialize(form)?;
    wtr.flush()?;

    Ok(format!("Hello {}!", form.fullname))
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(web::resource("/contact").route(web::post().to(contact)))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

我有以下错误:

error[E0277]: the trait bound `actix_web::types::form::Form<FormData>: _IMPL_DESERIALIZE_FOR_FormData::_serde::Serialize` is not satisfied
  --> src/main.rs:46:19
   |
46 |     wtr.serialize(form)?;
   |                   ^^^^ the trait `_IMPL_DESERIALIZE_FOR_FormData::_serde::Serialize` is not implemented for `actix_web::types::form::Form<FormData>`

error[E0277]: the trait bound `csv::Error: actix_http::error::ResponseError` is not satisfied
  --> src/main.rs:46:24
   |
46 |     wtr.serialize(form)?;
   |                        ^ the trait `actix_http::error::ResponseError` is not implemented for `csv::Error`
   |
   = note: required because of the requirements on the impl of `std::convert::From<csv::Error>` for `actix_http::error::Error`
   = note: required by `std::convert::From::from`

error: aborting due to 2 previous errors

使用的库:

[dependencies]
actix-web = "2.0.0"
actix-rt = "1.0.0"
serde = "1.0"
serde_derive = "1.0.110"
csv = "1.1"
7eumitmz

7eumitmz1#

您需要获取web::form数据的内部结构。

pub async fn contact(form: web::Form<FormData>) -> HttpResponse<Body> {
  let mut wtr = csv::Writer::from_writer(io::stdout());
  wtr.serialize(form.into_inner());
  wtr.flush();

  HttpResponse::Ok().body("".to_string())
}

相关问题