将文档对象的向量从 rust 返回到 python 失败。
我在 Rust 中有一个结构和方法实现,如下所示。
use mongodb::{
bson::{Bson, Document},
error::Error,
sync::Client,
};
use pyo3::prelude::*;
#[pyclass]
pub struct SampleStruct{
docs: Vec<Document>,
}
#[pymethods]
impl SampleStruct{
#[new]
pub fn new() -> Self {...}
pub fn a_method(&self, some_string: &str) -> Vec<&Document> {...}
}
以上失败并显示以下消息
error[E0277]: the trait bound `std::vec::Vec<&bson::document::Document>: pyo3::callback::IntoPyCallbackOutput<_>` is not satisfied
--> src/fail_demo.rs:55:1
|
55 | #[pymethods]
| ^^^^^^^^^^^^ the trait `pyo3::callback::IntoPyCallbackOutput<_>` is not implemented for `std::vec::Vec<&bson::document::Document>`
|
::: /home/demo/.cargo/registry/src/github.com-1ecc6299db9ec823/pyo3-0.11.1/src/callback.rs:169:8
|
169 | T: IntoPyCallbackOutput<U>,
| ----------------------- required by this bound in `pyo3::callback::convert`
|
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
最简单的方法是将 BSON 序列化为
bytes
,然后使用您选择的 BSON 库在 Python 中对其进行解码:
#[pyfunction]
fn bson_document<'py>(py: Python<'py>, key: &str, value: i32) -> PyResult<Bound<'py, PyBytes>> {
let document = doc! {
key: value,
"otherKey": "otherValue",
};
let bytes = bson::to_vec(&document).map_err(|err| PyValueError::new_err(err.to_string()))?;
Ok(PyBytes::new_bound(py, &bytes))
}
pymongo
:
import bson
doc = bson_document("myKey", -123)
print(bson.decode(doc))