gpt4 book ai didi

rust - 如何在 rocket.rs 中使 postgres 池连接全局化并使 FromRequest 自定义守卫异步?

转载 作者:行者123 更新时间:2023-12-03 11:38:13 25 4
gpt4 key购买 nike

我正在制作一个授权系统,它将实现来自网络框架火箭的 FromRequest 特征,这是制作自定义守卫所必需的。

我遇到的第一个问题是如何使连接成为全局连接。我应该将它转换为常量,以便可以从实现中的函数访问它,还是火箭中有缓存或 PgPool 连接的某种形式的存储(因为我使用的是 sqlx)可以访问和查询。

我遇到的第二个问题是使 FromRequest 函数异步。由于 sqlx 是原生异步 afaik,我不知道 rocket 是否还支持这个。我正在考虑制作一个 tokio 线程,或者 Rust 中是否有 .then() 版本,但我不知道

#[derive(Debug)]
struct User {
username: String,
password: String,
user_id: i16,
phone_number: String,
display_name: String,
//other fields omitted
}

impl<'a, 'r> FromRequest<'a, 'r> for &'a User {
type Error = !;

fn from_request(request: &'a Request<'r>) -> request::Outcome<&'a User, !> {
let user_result = request.local_cache(|| {
//..need to fetch user with sqlx [but sqlx is async]
//and later get cookies and check
});

user_result.as_ref().or_forward(())
}
}

最佳答案

对 Rocket 的异步支持在版本 0.5 中登陆。现在,您可以使用主分支:https://github.com/SergioBenitez/Rocket

在 Rocket 中处理这个用例的惯用方法是对数据库使用 rocket-contrib 适配器:https://docs.rs/rocket_contrib/0.4.7/rocket_contrib/databases/index.html#provided

您需要为您的数据库实现 Poolable Trait。这是相关文档:https://docs.rs/rocket_contrib/0.4.7/rocket_contrib/databases/trait.Poolable.html

Rocket 已经提供了以下特性:

diesel::MysqlConnection
diesel::PgConnection
diesel::SqliteConnection
postgres::Connection
mysql::Conn
rusqlite::Connection
rusted_cypher::GraphClient
redis::Connection

然后您可以像这样使用数据库宏:

use rocket_contrib::databases::postgres;

#[database("db_name")]
struct MyPgDatabase(postgres::Connection);

fn main() {
rocket::custom(config)
.attach(MyPgDatabase::fairing())
.launch();
}

然后您可以只使用此类型作为请求保护,然后检索数据库连接,因为上面的宏会自动为您生成 FromRequest 实现

#[get("/")]
fn my_handler(conn: MyPgDatabase) {
// ...
}

该宏还会生成一个Deref 实现,允许您访问内部连接类型。

供引用:
https://github.com/TatriX/realworld-rust-rocket : 一个很好的代码示例展示了这一点

关于rust - 如何在 rocket.rs 中使 postgres 池连接全局化并使 FromRequest 自定义守卫异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65754040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com