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
3 changes: 0 additions & 3 deletions python/rnet/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,6 @@ class SocketAddr:
"""

def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def ip(self) -> Union[ipaddress.IPv4Address, ipaddress.IPv6Address]:
r"""
Returns the IP address of the socket address.
Expand All @@ -592,7 +591,6 @@ class StatusCode:
"""

def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def as_int(self) -> int:
r"""
Return the status code as an integer.
Expand Down Expand Up @@ -1002,7 +1000,6 @@ class Message:
Returns the close code and reason of the message if it is a close message.
"""
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
@staticmethod
def text_from_json(json: Dict[str, Any]) -> Message:
r"""
Expand Down
1 change: 0 additions & 1 deletion python/rnet/cookie.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ class Cookie:
"""

def __str__(self) -> str: ...
def __repr__(self) -> str: ...

class Jar:
r"""
Expand Down
4 changes: 0 additions & 4 deletions python/rnet/header.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,6 @@ class HeaderMap:
"""Return a string representation of all headers."""
...

def __repr__(self) -> str:
"""Return a detailed string representation."""
...

def __new__(
cls, init: Optional[dict] = None, capacity: Optional[int] = None
) -> HeaderMap:
Expand Down
5 changes: 2 additions & 3 deletions src/client/async_impl/response/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use wreq::{Url, header, tls::TlsInfo};
use crate::{
buffer::{Buffer, BytesBuffer, PyBufferProtocol},
client::{SocketAddr, json::Json},
cookie::Cookie,
error::Error,
http::{StatusCode, Version, header::HeaderMap},
http::{Version, cookie::Cookie, header::HeaderMap, status::StatusCode},
};

/// A response from a request.
Expand Down Expand Up @@ -224,8 +223,8 @@ type InnerStreamer = Pin<Box<dyn Stream<Item = wreq::Result<bytes::Bytes>> + Sen
/// Used to stream response content.
/// Implemented in the `stream` method of the `Response` class.
/// Can be used in an asynchronous for loop in Python.
#[pyclass(subclass)]
#[derive(Clone)]
#[pyclass(subclass)]
pub struct Streamer(Arc<Mutex<Option<InnerStreamer>>>);

impl Deref for Streamer {
Expand Down
14 changes: 7 additions & 7 deletions src/client/async_impl/response/ws/message.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

use bytes::Bytes;
use pyo3::{
prelude::*,
Expand All @@ -12,8 +14,8 @@ use crate::{
};

/// A WebSocket message.
#[pyclass(subclass)]
#[derive(Clone)]
#[pyclass(subclass, str)]
pub struct Message(pub message::Message);

#[pymethods]
Expand Down Expand Up @@ -164,12 +166,10 @@ impl Message {
});
Message(msg)
}
}

fn __str__(&self) -> String {
format!("{:?}", self.0)
}

fn __repr__(&self) -> String {
self.__str__()
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
3 changes: 1 addition & 2 deletions src/client/async_impl/response/ws/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ use wreq::{

use crate::{
client::SocketAddr,
cookie::Cookie,
error::Error,
http::{StatusCode, Version, header::HeaderMap},
http::{Version, cookie::Cookie, header::HeaderMap, status::StatusCode},
};

type Sender = Arc<Mutex<Option<SplitSink<ws::WebSocket, ws::message::Message>>>>;
Expand Down
3 changes: 1 addition & 2 deletions src/client/blocking/response/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ use crate::{
async_impl::response::{Response, Streamer},
json::Json,
},
cookie::Cookie,
error::Error,
http::{StatusCode, Version, header::HeaderMap},
http::{Version, cookie::Cookie, header::HeaderMap, status::StatusCode},
};

/// A blocking response from a request.
Expand Down
3 changes: 1 addition & 2 deletions src/client/blocking/response/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ use crate::{
SocketAddr,
async_impl::response::{Message, WebSocket},
},
cookie::Cookie,
error::Error,
http::{StatusCode, Version, header::HeaderMap},
http::{Version, cookie::Cookie, header::HeaderMap, status::StatusCode},
};

/// A blocking WebSocket response.
Expand Down
16 changes: 8 additions & 8 deletions src/client/net.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::fmt;

use pyo3::{IntoPyObjectExt, prelude::*};

/// A IP socket address.
#[pyclass(eq)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[derive(Clone, Copy, PartialEq, Eq)]
#[pyclass(eq, str)]
pub struct SocketAddr(pub std::net::SocketAddr);

#[pymethods]
Expand All @@ -16,12 +18,10 @@ impl SocketAddr {
fn port(&self) -> u16 {
self.0.port()
}
}

fn __str__(&self) -> String {
self.0.to_string()
}

fn __repr__(&self) -> String {
self.__str__()
impl fmt::Display for SocketAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
2 changes: 1 addition & 1 deletion src/client/param/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use wreq::{Proxy, header::HeaderMap};
use wreq_util::EmulationOption;

use crate::{
cookie::Jar,
extractor::Extractor,
http::cookie::Jar,
tls::{SslVerify, TlsVersion},
};

Expand Down
2 changes: 1 addition & 1 deletion src/emulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ define_enum!(
);

/// A struct to represent the `EmulationOption` class.
#[pyclass(subclass)]
#[derive(Clone)]
#[pyclass(subclass)]
pub struct EmulationOption(pub wreq_util::EmulationOption);

#[pymethods]
Expand Down
21 changes: 11 additions & 10 deletions src/cookie.rs → src/http/cookie.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
fmt,
sync::{Arc, RwLock},
time::SystemTime,
};
Expand Down Expand Up @@ -29,17 +30,18 @@ define_enum!(
);

/// A single HTTP cookie.
#[pyclass(subclass)]

#[derive(Clone)]
#[pyclass(subclass, str)]
pub struct Cookie(pub RawCookie<'static>);

/// A good default `CookieStore` implementation.
///
/// This is the implementation used when simply calling `cookie_store(true)`.
/// This type is exposed to allow creating one and filling it with some
/// existing cookies more easily, before creating a `Client`.
#[pyclass(subclass)]
#[derive(Clone, Default)]
#[pyclass(subclass)]
pub struct Jar(Arc<RwLock<cookie_store::CookieStore>>);

// ===== impl Cookie =====
Expand Down Expand Up @@ -177,17 +179,10 @@ impl Cookie {
None | Some(Expiration::Session) => None,
}
}

fn __str__(&self) -> String {
self.0.to_string()
}

fn __repr__(&self) -> String {
self.__str__()
}
}

impl Cookie {
/// Parse cookies from a `HeaderMap`.
pub fn extract_headers_cookies(headers: &HeaderMap) -> Vec<Cookie> {
headers
.get_all(header::SET_COOKIE)
Expand All @@ -206,6 +201,12 @@ impl Cookie {
}
}

impl fmt::Display for Cookie {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}

// ===== impl Jar =====

impl CookieStore for Jar {
Expand Down
71 changes: 38 additions & 33 deletions src/http/header.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

use pyo3::{
prelude::*,
pybacked::{PyBackedBytes, PyBackedStr},
Expand All @@ -8,32 +10,43 @@ use wreq::header::{self, HeaderName, HeaderValue};
use crate::buffer::{HeaderNameBuffer, HeaderValueBuffer, PyBufferProtocol};

/// A HTTP header map.
#[pyclass(subclass)]
#[pyclass(subclass, str)]
#[derive(Clone)]
pub struct HeaderMap(pub header::HeaderMap);

#[pymethods]
impl HeaderMap {
/// Creates a new `HeaderMap` from an optional dictionary.
#[new]
#[pyo3(signature = (init=None, capacity=None))]
fn new(init: Option<&Bound<'_, PyDict>>, capacity: Option<usize>) -> Self {
#[pyo3(signature = (dict=None, capacity=None))]
fn new(dict: Option<&Bound<'_, PyDict>>, capacity: Option<usize>) -> Self {
let mut headers = capacity
.map(header::HeaderMap::with_capacity)
.unwrap_or_default();

// This section of memory might be retained by the Rust object,
// and we want to prevent Python's garbage collector from managing it.
if let Some(dict) = init {
if let Some(dict) = dict {
for (name, value) in dict.iter() {
if let (Ok(Ok(name)), Ok(Ok(value))) = (
name.extract::<PyBackedStr>()
.map(|n| HeaderName::from_bytes(n.as_bytes())),
value
.extract::<PyBackedStr>()
.map(HeaderValue::from_maybe_shared),
) {
headers.insert(name, value);
}
let name = match name
.extract::<PyBackedStr>()
.ok()
.and_then(|n| HeaderName::from_bytes(n.as_bytes()).ok())
{
Some(n) => n,
None => continue,
};

let value = match value
.extract::<PyBackedStr>()
.ok()
.and_then(|v| HeaderValue::from_maybe_shared(v).ok())
{
Some(v) => v,
None => continue,
};

headers.insert(name, value);
}
}

Expand All @@ -52,16 +65,13 @@ impl HeaderMap {
key: PyBackedStr,
default: Option<PyBackedBytes>,
) -> Option<Bound<'py, PyAny>> {
match self.0.get::<&str>(key.as_ref()).cloned().or_else(|| {
default
.map(HeaderValue::from_maybe_shared)
.transpose()
.ok()
.flatten()
}) {
Some(value) => HeaderValueBuffer::new(value).into_bytes_ref(py).ok(),
None => None,
}
let value = self
.0
.get::<&str>(key.as_ref())
.cloned()
.or_else(|| default.and_then(|d| HeaderValue::from_maybe_shared(d).ok()));

value.and_then(|v| HeaderValueBuffer::new(v).into_bytes_ref(py).ok())
}

/// Returns a view of all values associated with a key.
Expand Down Expand Up @@ -150,8 +160,7 @@ impl HeaderMap {
self.0.is_empty()
}

/// Clears the map, removing all key-value pairs. Keeps the allocated memory
/// for reuse.
/// Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
#[inline]
fn clear(&mut self) {
self.0.clear();
Expand Down Expand Up @@ -191,15 +200,11 @@ impl HeaderMap {
inner: self.0.keys().cloned().collect(),
}
}
}

#[inline]
fn __str__(&self) -> String {
format!("{:?}", self.0)
}

#[inline]
fn __repr__(&self) -> String {
self.__str__()
impl fmt::Display for HeaderMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
pub mod cookie;
pub mod header;
mod status;
pub mod status;

use pyo3::prelude::*;

pub use self::status::StatusCode;

define_enum!(
/// An HTTP version.
const,
Expand Down
Loading
Loading