Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ name = "rnet"
crate-type = ["cdylib", "rlib"]
doctest = false

[features]
logging = ["dep:pyo3-log", "dep:log"]

[dependencies]
tokio = { version = "1.0", features = ["sync"] }
pyo3 = { version = "0.23.0", features = [
Expand All @@ -25,7 +28,9 @@ pyo3 = { version = "0.23.0", features = [
"experimental-inspect",
] }
pyo3-async-runtimes = { version = "0.23.0", features = ["tokio-runtime"] }
pyo3-log = { version = "0.12.1", optional = true }
pyo3-stub-gen = "0.7.0"
log = { version = "0.4.25", optional = true }
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

> 🚀 Help me work seamlessly with open source sharing by [sponsoring me on GitHub](https://github.com/0x676e67/0x676e67/blob/main/SPONSOR.md)

Asynchronous Python HTTP client with Black Magic, powered by FFI from [rquest](https://github.com/0x676e67/rquest). This library can mimic the TLS and HTTP2 configurations of popular browsers like Chrome, Safari, Firefox, and OkHttp.
An asynchronous Python HTTP client with Black Magic, powered by FFI from [rquest](https://github.com/0x676e67/rquest), capable of mimicking `TLS` and `HTTP2` configurations of popular browsers like `Chrome`, `Safari`, `Firefox`, and `OkHttp`.

## Features

Expand Down
49 changes: 49 additions & 0 deletions examples/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import asyncio
import logging
import colorlog
from rnet import Impersonate, Client


formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
},
secondary_log_colors={},
style='%'
)

handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = colorlog.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

async def main():
client = Client(
impersonate=Impersonate.Firefox133,
user_agent="rnet",
async_dns=True,
)
resp = await client.get("https://httpbin.org/stream/20")
print("Status Code: ", resp.status_code)
print("Version: ", resp.version)
print("Response URL: ", resp.url)
print("Headers: ", resp.headers.to_dict())
print("Content-Length: ", resp.content_length)
print("Encoding: ", resp.encoding)
print("Remote Address: ", resp.remote_addr)
streamer = resp.stream()
async for chunk in streamer:
print("Chunk: ", chunk)
await asyncio.sleep(0.1)


if __name__ == "__main__":
asyncio.run(main())
9 changes: 8 additions & 1 deletion src/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,14 @@ where
HickoryDnsResolver::new(strategy.into())
.map(Arc::new)
.map_err(|err| {
eprintln!("failed to initialize the DNS resolver: {}", err);
#[cfg(feature = "logging")]
{
log::error!("failed to initialize the DNS resolver: {}", err);
}
#[cfg(not(feature = "logging"))]
{
eprintln!("failed to initialize the DNS resolver: {}", err);
}
"failed to initialize the DNS resolver"
})
})
Expand Down
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ mod response;
mod types;

use client::Client;
#[cfg(feature = "logging")]
use log::LevelFilter;
use param::{ClientParams, RequestParams, UpdateClientParams, WebSocketParams};
use pyo3::prelude::*;
#[cfg(feature = "logging")]
use pyo3_log::{Caching, Logger};
use pyo3_stub_gen::{define_stub_info_gatherer, derive::*};
use response::{Message, Response, Streamer, WebSocket};
use types::{
Expand Down Expand Up @@ -280,6 +284,18 @@ fn websocket(

#[pymodule(gil_used = false)]
fn rnet(m: &Bound<'_, PyModule>) -> PyResult<()> {
// A good place to install the Rust -> Python logger.
#[cfg(feature = "logging")]
{
let handle = Logger::new(m.py(), Caching::LoggersAndLevels)?
.filter(LevelFilter::Trace)
.install()
.expect("Someone installed a logger before rnet.");

// Some time in the future when logging changes, reset the caches:
handle.reset();
}

m.add_class::<Method>()?;
m.add_class::<Version>()?;
m.add_class::<HeaderMap>()?;
Expand Down