Распараллеливание запросов GET с использованием PyO3Python

Программы на Python
Ответить
Anonymous
 Распараллеливание запросов GET с использованием PyO3

Сообщение Anonymous »

Я пытаюсь оптимизировать некоторый код Python с помощью библиотеки PyO3, которая позволяет мне писать собственный код Rust, который я могу импортировать в свой код Python. В частности, я пытаюсь парализовать запрос нескольких URL-адресов в Rust, которые затем импортирую в код Python, чтобы параллельно получать несколько URL-адресов, которые затем анализирую с помощью BeautifulSoup. Это код Rust, который вызывает у меня некоторые проблемы.
use pyo3::prelude::*;
use tokio::runtime::Runtime;
use reqwest;
use futures::future;

// Function to fetch URLs in parallel
#[pyfunction]
fn fetch_urls(urls: Vec) -> PyResult {
let rt = Runtime::new().unwrap(); // Create a Tokio runtime
let responses = rt.block_on(async {
let futures = urls.into_iter().map(|url| {
async {
reqwest::get(&url).await.ok().and_then(|resp| Some(resp.text()))
}
});
future::join_all(futures).await
});
Ok(responses.into_iter().filter_map(|x| x).collect())
}

// PyO3 module
#[pymodule]
fn rust_requests(_py: Python, m: &PyModule) -> PyResult {
m.add_function(wrap_pyfunction!(fetch_urls, m)?)?;
Ok(())
}

Это ошибки, которые я получаю при запуске maturin development
error[E0308]: mismatched types
--> src/lib.rs:13:63
|
13 | reqwest::get(&url).await.ok().and_then(|resp| resp.text())
| ^^^^^^^^^^^ expected `Option`, found future
|
help: try wrapping the expression in `Some`
|
13 | reqwest::get(&url).await.ok().and_then(|resp| Some(resp.text()))
| +++++ +

error[E0599]: no method named `add_function` found for reference `&pyo3::types::PyModule` in the current scope
--> src/lib.rs:24:7
|
24 | m.add_function(wrap_pyfunction!(fetch_urls, m)?)?;
| ^^^^^^^^^^^^ method not found in `&PyModule`

error[E0277]: the trait bound `&pyo3::types::PyModule: WrapPyFunctionArg` is not implemented for `&pyo3::types::PyModule`
| required by a bound introduced by this call
|
= help: the following other types implement trait `WrapPyFunctionArg
pyo3::Borrowed
pyo3::Python
&pyo3::Borrowed
= note: this error originates in the macro `wrap_pyfunction` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: the trait bound `&pyo3::types::PyModule: From` is not satisfied
--> src/lib.rs:22:1
|
22 | #[pymodule]
| ^^^^^^^^^^^ the trait `From` is not implemented for `&pyo3::types::PyModule`, which is required by `BoundRef: Into`
|
= note: required for `BoundRef` to implement `Into`
= note: this error originates in the attribute macro `pymodule` (in Nightly builds, run with -Z macro-backtrace for more info)

Some errors have detailed explanations: E0277, E0308, E0599.

Я не знаю, как исправить эти ошибки, поскольку мои знания Rust ограничены, поэтому буду благодарен за любую помощь. Вот сопроводительный код Cargo.toml и Python
[package]
name = "python-rust-interop"
version = "0.1.0"
edition = "2021"

[lib]
name = "rust_requests"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.22", features = ["extension-module"] }
tokio = { version = "1.41.0", features = ["full"] } # Add tokio with all features
reqwest = { version = "0.11", features = ["json"] } # Add reqwest with JSON support
futures = "0.3"

from rust_requests import fetch_urls
from bs4 import BeautifulSoup

# List of URLs to scrape
urls = ["http://example.com", "http://example.org"]

# Fetch data using Rust
html_responses = fetch_urls(urls)

# Parse each response with BeautifulSoup
for html in html_responses:
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text)


Подробнее здесь: https://stackoverflow.com/questions/792 ... using-pyo3
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»