RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-334127

Егор Никоноров's questions

Martin Hope
Exdet
Asked: 2024-01-25 20:11:37 +0000 UTC

从请求中提取“数据”值的中间件(rust)

  • 5

我应该以 { "data":{ ... } } 的形式接收对 api 的请求。我经常需要从数据中获取所有必要的信息。在请求主体沿着路线进一步前进之前,我怎样才能做到这一点?

#[derive(Debug, Deserialize)]
pub struct ApiData<T> {
    pub data: T,
}

struct ExtractData;

#[rocket::async_trait]
impl<T> Fairing for ExtractData
    where
        T: FromRequest<'static>,
{
    fn info(&self) -> Info {
        Info {
            name: "ExtractData",
            kind: Kind::Request,
        }
    }

    async fn on_request<'a>(&self, req: &'a mut Request<'_>, _: &'a Data<'_>) {
        if let Some(data) = req.guard::<ApiData<T>>().succeeded() {
            req.local_cache(|| data.data);
        } else {
            req.set_abort(Some(Status::BadRequest));
        }
    }
}

#[launch]
async fn rocket() -> _ {
    let db = MongoRepo::init().await;
    rocket::build().manage(db)
        .attach(ExtractData)
        .mount("/api/", routes![get_files_in_directories])
        .mount("/api/usepi/patterns", routes![create_pattern])
        .mount(
            "/api/usepi/patterns/icons",
            FileServer::from(Path::new("./src/icons")),
        )
}

我正在尝试以这种方式实现它,但总是存在类型错误

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:54:6
   |
54 | impl<T> Fairing for ExtractData
   |      ^ unconstrained type parameter

我不知道该怎么做,请告诉我

rust
  • 1 个回答
  • 34 Views
Martin Hope
Exdet
Asked: 2024-01-23 02:26:50 +0000 UTC

如何连接到 mongoDB?(锈)

  • 5

我自己铆接了这样一个结构,然后根据我的想法,我可以开发它

| src /
|       - api /
|       |       -patterns /
|       |       |       - mod.rs
|       |       |       - patterns.rs
|       |       |_________
|       |        - mod.rs
|       |______________
|    
|       - models /
|       |        - mod.rs
|       |        - pattern_model.rs
|       |        - pattern_asset_model.rs
|       |        - pattern_folder_model.rs
|       |        - device_model.rs
|       |        - device_asset_model.rs
|       |        - device_folder_model.rs
|       |        - universal_pattern_model.rs
|       |_________________
|
|       - repository /
|       |       | - mod.rs
|       |       | - mongodb_repo.rs
|       |_________________
|
|       - img /
|       |       
|       |       
|       |_________________
|
|       - .env      

|       - main.rs

|_________________________
- Cargo.lock
- Cargo.toml


api - 旨在调整 API 处理程序。模型 - 旨在调制数据逻辑。存储库 - 旨在调整数据库逻辑。但这不是问题的重点(尽管如果有人有任何意见,请不要害羞)。

我正在尝试通过 Rocket 从数据库启动一台服务器,然后简单地将一条记录添加到集合中。

// main.rs 
mod api;
mod models;
mod repository;

#[macro_use]
extern crate rocket;

use api::patterns::patterns::{create_pattern};
use repository::mongodb_repo::MongoRepo;


#[launch]
fn rocket() -> _ {
    let db = MongoRepo::init();
    rocket::build().manage(db)
        .mount("/api/usepi/patterns", routes![create_pattern])
}

这是数据库初始化代码..

//mongodb_repo.rs
use std::env;


extern crate dotenv;
use dotenv::dotenv;

use mongodb::{Client, Collection, options::ClientOptions};
use mongodb::error::Error;
use mongodb::results::InsertOneResult;

use crate::models::pattern_model::Pattern as ModelPattern;

pub struct MongoRepo {
    pattern_collection: Collection<ModelPattern>,
}

impl MongoRepo {

    pub async fn init() -> Self {
            dotenv().ok();
            let mongodb_uri = dotenv::var("MONGODB_URI");
            println!("AAAAAA {:?}",mongodb_uri);
            let client_options = ClientOptions::parse(mongodb_uri).await?;
            let client = Client::with_options(client_options)?;
            let db = client.database("RustBlueTractorDB");
            let pattern_collection: Collection<ModelPattern> = db.collection("Pattern");
            MongoRepo { pattern_collection }
        }

    .....

}

但这样的错误总是会发生:

error[E0277]: the trait bound `Result<std::string::String, dotenv::Error>: AsRef<str>` is not satisfied
    --> src/repository/mongodb_repo.rs:26:55
     |
26   |             let client_options = ClientOptions::parse(mongodb_uri).await?;
     |                                  -------------------- ^^^^^^^^^^^ the trait `AsRef<str>` is not implemented for `Result<std::string::String, dotenv::Error>`
     |                                  |
     |                                  required by a bound introduced by this call
     |
note: required by a bound in `ClientOptions::parse`

当你修复一件事时,会出现一个错误,并显示“rocket::build().manage(db)..”,然后又回到这一点。我尝试按照手册进行操作(虽然数量不是很多,但由于各种原因它们都不起作用)。在 .env 中我有..

MONGODB_URI=mongodb://192.168.1.63:27018/

这是pattern_model 中的内容...

use mongodb::bson::oid::ObjectId;
use serde::{Serialize, Deserialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct PatternRequest {
    pub data: Pattern,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Pattern {
    #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
    pub id: Option<ObjectId>,
    pub title: String,
    pub description: String,
    pub icon: String,
    pub pattern: String,
    pub create_date: String,
    pub update_date: String,
    pub version: String,
    pub favourite: bool,
}

还有 toml:

[package]
name = "rust"
version = "0.1.0"
edition = "2021"

[dependencies]
rocket = {version = "0.5.0-rc.2", features = ["json"]}
serde = "1.0.136"
dotenv = "0.15.0"
chrono = "0.4.31"

[dependencies.mongodb]
version = "2.8.0"
default-features = false
features = ["async-std-runtime"]

问题是,我该如何做到这一点?我出于紧急需要而从nestJS切换过来,如果通常的功能看起来可以工作,那么这是一个大问题,我不明白。提前致谢!

mongodb
  • 1 个回答
  • 28 Views
Martin Hope
Exdet
Asked: 2023-10-30 15:34:44 +0000 UTC

如何在本地网络上设置自签名 ssl 证书?

  • 5

如何设置一个自签名的ssl证书,以便本地网络上的两台机器可以互相通信。(我们正在测试API,需要ssl来读取cookie)

openssl.cnf:

[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
organizationName = text
organizationalUnitName = text
localityName = text
stateOrProvinceName  = text
countryName = Ru
commonName = localhost
emailAddress = [email protected]

[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = *
IP.1 = 192.168.1.63
IP.2 = 192.168.1.69

我创建一个证书和密钥:

openssl req -x509 -newkey rsa:2048 -keyout private-key.pem -out certificate.pem -days 365 -config openssl.cnf

在第二台计算机上安装此证书并使其受信任后,出现错误“net::ERR_CERT_COMMON_NAME_INVALID”。

javascript
  • 1 个回答
  • 36 Views
Martin Hope
Егор Никоноров
Asked: 2020-04-17 00:48:22 +0000 UTC

如何在数组中显示所选对象的极值点坐标?

  • 2

物体识别有一段代码:

from imageai.Detection import VideoObjectDetection
import os

execution_path = os.getcwd()

detector = VideoObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath( os.path.join(execution_path , "yolo.h5"))
detector.loadModel()

video_path = detector.detectObjectsFromVideo(
    input_file_path = os.path.join(execution_path, "Car - 2165.mp4"),
    output_file_path = os.path.join(execution_path, "traffic_detected"),
    frames_per_second = 20,
    log_progress = True
)

assert isinstance(video_path, object)
print(video_path)   

如何在数组(具体来说,矩形等)中显示所选对象的极值点坐标?

python
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5