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
47 changes: 45 additions & 2 deletions src/client/body/json.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
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},
};

/// 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>),
Expand All @@ -35,6 +40,44 @@ struct JsonVisitor;

// ===== 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
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 ",
]