Skip to content

Commit

Permalink
Add a x-www-form-urlencoded url encoded serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
mardiros committed Jan 20, 2024
1 parent 70b581a commit dd2d49c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/blacksmith/service/request_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Union,
cast,
)
from urllib.parse import urlencode

from pydantic import BaseModel, SecretBytes, SecretStr
from pydantic.fields import FieldInfo
Expand Down Expand Up @@ -64,6 +65,14 @@ def serialize(self, body: Dict[str, Any] | Sequence[Any]) -> str:
return json.dumps(body, cls=JSONEncoder)


class UrlencodedRequestSerializer(AbstractRequestBodySerializer):
def accept(self, content_type: str) -> bool:
return content_type == "application/x-www-form-urlencoded"

def serialize(self, body: Dict[str, Any] | Sequence[Any]) -> str:
return urlencode(body, doseq=True)


class JSONEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
for typ, serializer in ENCODERS_BY_TYPE.items():
Expand Down Expand Up @@ -120,7 +129,10 @@ def serialize_part(req: "Request", part: Dict[IntStr, Any]) -> Dict[str, simplet
}


SERIALIZERS: list[AbstractRequestBodySerializer] = [JsonRequestSerializer()]
SERIALIZERS: list[AbstractRequestBodySerializer] = [
JsonRequestSerializer(),
UrlencodedRequestSerializer(),
]
"""Serializers to """


Expand Down
21 changes: 21 additions & 0 deletions tests/unittests/test_request_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
QUERY,
JSONEncoder,
JsonRequestSerializer,
UrlencodedRequestSerializer,
get_location,
serialize_body,
serialize_part,
Expand Down Expand Up @@ -235,6 +236,16 @@ def test_serializer_request(params: Mapping[str, Any]):
"accept": "text/xml",
"expected": False,
},
{
"srlz": UrlencodedRequestSerializer(),
"accept": "application/x-www-form-urlencoded",
"expected": True,
},
{
"srlz": UrlencodedRequestSerializer(),
"accept": "text/xml",
"expected": False,
},
],
)
def test_request_serializer_accept(params: Mapping[str, Any]):
Expand All @@ -250,6 +261,16 @@ def test_request_serializer_accept(params: Mapping[str, Any]):
"data": {"foo": "bar"},
"expected": '{"foo": "bar"}',
},
{
"srlz": UrlencodedRequestSerializer(),
"data": {"foo": "bar"},
"expected": "foo=bar",
},
{
"srlz": UrlencodedRequestSerializer(),
"data": {"foo": ["bar", "baz"]},
"expected": "foo=bar&foo=baz",
},
],
)
def test_request_serializer_serialize(params: Mapping[str, Any]):
Expand Down

0 comments on commit dd2d49c

Please sign in to comment.