1

我正在尝试将 rust 异步函数导出到 python。

这就是我想在我的 python 文件中使用的方式。

from rust_lib import get_weather

async def call_me():
    weather = await get_weather()
    print(weather.current_tmp)

在 Rust 中,我确实喜欢

#[pyclass]
#[derive(Debug, Default)]
struct Weather {
    #[pyo3(get)]
    current_tmp: String,
}

async fn get_weather() -> Result<Weather, reqwest::Error> {
    let client = reqwest::Client::builder()
        .danger_accept_invalid_certs(true)
        .connect_timeout(Duration::from_secs(2))
        .build()?;

    let res = client.get(url).header(USER_AGENT, "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36").send().await?;
    let body = res.text().await?;

    // HTML Parse
    let mut weather: Weather = Default::default();

    let document = Html::parse_document(&body);

   // some parsing

    Ok(weather)
}

但是在这里我得到了这个错误future cannot be sent between threads safely

#[pyfunction]
fn get_weather(py: Python) -> PyResult<&PyAny> {
    pyo3_asyncio::tokio::future_into_py(py, async move {
        let weather = weather_parse().await.unwrap().into_py(py);
        Ok(weather)
    })
}

在这里卡了很长时间,甚至不知道我在做什么..

提前致谢!

4

0 回答 0