Lui*_*eis 0 gnuplot rust actix-web
我正在尝试使用一个名为 plot 的端点设置一个简单的 actix-web 服务器。它本质上只是消耗一些数据,用 gnuplot 绘制它并返回结果 PNG 的字节。问题是,正如您将在代码中看到的那样,我还没有找到一种方法可以在内存中完成所有这些操作,这意味着我必须将文件持久保存到磁盘,将其重新打开到阅读器中,然后将响应发回。根据并发级别,我将开始获取{ code: 24, kind: Other, message: "Too many open files" }消息。
有谁知道我将如何做到这一点,以便整个过程在内存中完成?我在用:
actix-web = "3"
gnuplot = "0.0.37"
image = "0.23.12"
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,这是代码:
use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};
use gnuplot::{AxesCommon, Color, Figure, LineWidth};
use image::io::Reader;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::any::type_name;
use std::collections::HashMap;
use std::fs;
#[post("/")]
async fn plot(req_body: web::Json<HashMap<String, Vec<f64>>>) -> impl Responder {
let data = req_body.get("data").unwrap();
let mut fg = Figure::new();
let fid: String = thread_rng().sample_iter(&Alphanumeric).take(10).collect();
let fname: String = format!("./{fid}.png", fid = fid);
fg.set_terminal("pngcairo", &fname);
let ax = fg.axes2d();
ax.set_border(false, &[], &[]);
ax.set_pos(0.0, 0.0);
ax.set_x_ticks(None, &[], &[]);
ax.set_y_ticks(None, &[], &[]);
let x: Vec<usize> = (1..data.len()).collect();
ax.lines(&x, data, &[LineWidth(4.0), Color("black")]);
fg.set_post_commands("unset output").show();
let image = Reader::open(&fname).unwrap().decode().unwrap();
let mut bytes: Vec<u8> = Vec::new();
image.write_to(&mut bytes, image::ImageOutputFormat::Png);
fs::remove_file(fname);
HttpResponse::Ok().body(bytes)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(plot))
.bind("127.0.0.1:8080")?
.run()
.await
}
Run Code Online (Sandbox Code Playgroud)
为避免创建文件,您可以执行 Akihito KIRISAKI 所描述的操作。您可以通过调用set_terminal()而不是文件名来完成此操作,而是传递一个空字符串。然后你创建一个Command和echo()进入stdin.
use std::process::{Command, Stdio};
#[post("/")]
async fn plot(req_body: web::Json<HashMap<String, Vec<f64>>>) -> impl Responder {
...
fg.set_terminal("pngcairo", "");
...
fg.set_post_commands("unset output");
let mut child = Command::new("gnuplot")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("expected gnuplot");
let mut stdin = child.stdin.take().expect("expected stdin");
fg.echo(&mut stdin);
// Drop `stdin` such that it is flused and closed,
// otherwise some programs might block until stdin
// is closed.
drop(stdin);
let output = child.wait_with_output().unwrap();
let png_image_data = output.stdout;
HttpResponse::Ok().body(png_image_data)
}
Run Code Online (Sandbox Code Playgroud)
您还需要删除对 的调用show()。
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |