Skip to content
Open
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
129 changes: 115 additions & 14 deletions src/client/body/json.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
use std::fmt;

use indexmap::IndexMap;
use pyo3::{FromPyObject, prelude::*, pybacked::PyBackedStr};
use pyo3::{
FromPyObject,
prelude::*,
pybacked::PyBackedStr,
types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple},
};
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{Error, MapAccess, SeqAccess, Visitor},
de::{DeserializeSeed, Error, MapAccess, SeqAccess, Visitor},
ser::SerializeMap,
};

/// Represents a JSON value for HTTP requests.
/// Supports objects, arrays, numbers, strings, booleans, and null.
#[derive(FromPyObject, IntoPyObject, Serialize)]
#[derive(IntoPyObject, Serialize)]
#[serde(untagged)]
pub enum Json {
Object(IndexMap<JsonString, Json>),
Object(JsonObject),
Boolean(bool),
Number(isize),
Float(f64),
Expand All @@ -23,18 +28,100 @@ pub enum Json {

/// A JSON string: borrowed from Python when serializing a request body, owned when
/// deserializing a response.
#[derive(IntoPyObject, PartialEq, Eq, Hash)]
#[derive(IntoPyObject)]
pub enum JsonString {
PyString(PyBackedStr),
RustString(String),
}

pub struct JsonObject(Vec<(JsonString, Json)>);

/// Builds a [`Json`] in one pass; an untagged derive would buffer every value and then try
/// each variant in turn.
struct JsonVisitor;
struct JsonVisitor<'a>(&'a mut Vec<(JsonString, Json)>);

// ===== impl JsonObject =====

impl FromPyObject<'_, '_> for JsonObject {
type Error = PyErr;

fn extract(ob: Borrowed<PyAny>) -> PyResult<Self> {
let dict = ob.cast::<PyDict>()?;
let mut members = Vec::with_capacity(dict.len());
for (k, v) in dict.iter() {
members.push((k.extract()?, v.extract()?));
}
Ok(JsonObject(members))
}
}

impl<'py> IntoPyObject<'py> for JsonObject {
type Target = PyDict;
type Output = Bound<'py, PyDict>;
type Error = PyErr;

fn into_pyobject(self, py: Python<'py>) -> PyResult<Self::Output> {
let dict = PyDict::new(py);
for (k, v) in self.0 {
dict.set_item(k, v)?;
}
Ok(dict)
}
}

impl Serialize for JsonObject {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(self.0.len()))?;
for (k, v) in &self.0 {
map.serialize_entry(k, v)?;
}
map.end()
}
}

// ===== impl JsonString =====

impl FromPyObject<'_, '_> for Json {
type Error = PyErr;

fn extract(ob: Borrowed<PyAny>) -> PyResult<Self> {
if ob.is_instance_of::<PyString>() {
return ob.extract().map(Json::String);
}
if ob.is_instance_of::<PyBool>() {
return ob.extract().map(Json::Boolean);
}
if ob.is_instance_of::<PyInt>() {
return ob
.extract()
.map(Json::Number)
.or_else(|_| ob.extract().map(Json::Float));
}
if ob.is_instance_of::<PyFloat>() {
return ob.extract().map(Json::Float);
}
if ob.is_none() {
return Ok(Json::Null(None));
}
if ob.is_instance_of::<PyDict>() {
return ob.extract().map(Json::Object);
}
if ob.is_instance_of::<PyList>() || ob.is_instance_of::<PyTuple>() {
return ob.extract().map(Json::Array);
}
ob.extract()
.map(Json::Object)
.or_else(|_| ob.extract().map(Json::Boolean))
.or_else(|_| ob.extract().map(Json::Number))
.or_else(|_| ob.extract().map(Json::Float))
.or_else(|_| ob.extract().map(Json::String))
.or_else(|_| ob.extract().map(Json::Array))
}
}

impl FromPyObject<'_, '_> for JsonString {
type Error = PyErr;

Expand Down Expand Up @@ -75,13 +162,25 @@ impl<'de> Deserialize<'de> for Json {
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(JsonVisitor)
deserializer.deserialize_any(JsonVisitor(&mut Vec::new()))
}
}

// ===== impl JsonVisitor =====

impl<'de> Visitor<'de> for JsonVisitor {
impl<'de> DeserializeSeed<'de> for JsonVisitor<'_> {
type Value = Json;

#[inline]
fn deserialize<D>(self, deserializer: D) -> Result<Json, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(self)
}
}

impl<'de> Visitor<'de> for JsonVisitor<'_> {
type Value = Json;

fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down Expand Up @@ -123,17 +222,19 @@ impl<'de> Visitor<'de> for JsonVisitor {

fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Json, A::Error> {
let mut values = Vec::new();
while let Some(value) = seq.next_element()? {
while let Some(value) = seq.next_element_seed(JsonVisitor(&mut *self.0))? {
values.push(value);
}
Ok(Json::Array(values))
}

fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Json, A::Error> {
let mut values = IndexMap::new();
while let Some((key, value)) = map.next_entry()? {
values.insert(key, value);
let stack = self.0;
let start = stack.len();
while let Some(key) = map.next_key()? {
let value = map.next_value_seed(JsonVisitor(&mut *stack))?;
stack.push((key, value));
}
Ok(Json::Object(values))
Ok(Json::Object(JsonObject(stack.drain(start..).collect())))
}
}
35 changes: 33 additions & 2 deletions src/client/param.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use indexmap::IndexMap;
use pyo3::{FromPyObject, pybacked::PyBackedStr};
use pyo3::{
FromPyObject,
prelude::*,
pybacked::PyBackedStr,
types::{PyBool, PyFloat, PyInt, PyString},
};
use serde::{
Serialize, Serializer,
ser::{SerializeMap, SerializeSeq},
Expand All @@ -15,14 +20,40 @@ pub enum Params {

/// A scalar parameter value: `bool`, `int`, `float` or `str`, serialized as its text form
/// (`true`/`false` for booleans).
#[derive(FromPyObject)]
pub enum ParamValue {
Boolean(bool),
Number(isize),
Float64(f64),
String(PyBackedStr),
}

impl FromPyObject<'_, '_> for ParamValue {
type Error = PyErr;

fn extract(ob: Borrowed<PyAny>) -> PyResult<Self> {
if ob.is_instance_of::<PyString>() {
return ob.extract().map(ParamValue::String);
}
if ob.is_instance_of::<PyBool>() {
return ob.extract().map(ParamValue::Boolean);
}
if ob.is_instance_of::<PyInt>() {
return ob
.extract()
.map(ParamValue::Number)
.or_else(|_| ob.extract().map(ParamValue::Float64));
}
if ob.is_instance_of::<PyFloat>() {
return ob.extract().map(ParamValue::Float64);
}
ob.extract()
.map(ParamValue::Boolean)
.or_else(|_| ob.extract().map(ParamValue::Number))
.or_else(|_| ob.extract().map(ParamValue::Float64))
.or_else(|_| ob.extract().map(ParamValue::String))
}
}

impl Serialize for ParamValue {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
53 changes: 53 additions & 0 deletions tests/request_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

import pytest
import wreq
from wreq import Version
Expand Down Expand Up @@ -205,3 +207,54 @@ def file_to_bytes_stream(file_path):
async with resp:
json = await resp.json()
assert json["data"] in open("README.md").read()


@pytest.mark.asyncio
async def test_json_and_query_value_types():
requests = asyncio.Queue()

async def handle(reader, writer):
head = await reader.readuntil(b"\r\n\r\n")
length = next(
(
int(line.split(b":")[1])
for line in head.split(b"\r\n")
if line.lower().startswith(b"content-length:")
),
0,
)
requests.put_nowait(
head.split(b" ")[1] + b" " + await reader.readexactly(length)
)
writer.write(
b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
await writer.drain()
writer.close()

server = await asyncio.start_server(handle, "127.0.0.1", 0)
url = f"http://127.0.0.1:{server.sockets[0].getsockname()[1]}/"
body = {
"b": True,
"i": 1,
"f": 1.5,
"s": "x",
"n": None,
"l": [1, "a"],
"t": (False,),
"o": {"k": {}},
}
try:
await (await client.post(url, json=body)).close()
await (
await client.get(url, query={"b": False, "i": 2, "f": 0.5, "s": "y"})
).close()
sent = [await asyncio.wait_for(requests.get(), 5) for _ in range(2)]
finally:
server.close()
await server.wait_closed()

assert sent == [
b'/ {"b":true,"i":1,"f":1.5,"s":"x","n":null,"l":[1,"a"],"t":[false],"o":{"k":{}}}',
b"/?b=false&i=2&f=0.5&s=y ",
]