Skip to content

Commit

Permalink
Add support for GET lists.
Browse files Browse the repository at this point in the history
  • Loading branch information
luhn committed Jul 26, 2024
1 parent deb0c00 commit 4cffd1f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
8 changes: 6 additions & 2 deletions pyramid_marshmallow/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from marshmallow import Schema, ValidationError
from marshmallow import Schema, ValidationError, fields
from pyramid.response import Response
from pyramid.viewderivers import VIEW

Expand Down Expand Up @@ -48,7 +48,11 @@ def wrapped(context, request):
if request.method == "GET":
data = dict()
for k, v in request.GET.items():
data[k] = v
field = schema.fields.get(k)
if isinstance(field, fields.List):
data.setdefault(k, []).append(v)
else:
data[k] = v
else:
data = request.json_body
request.data = schema.load(data)
Expand Down
19 changes: 18 additions & 1 deletion tests/sampleapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ class AlbumSchema(Schema):
"""

title = fields.Str()
title = fields.String()
release_date = fields.Date(allow_null=True)
artists = fields.List(fields.String())


class Root(dict):
Expand Down Expand Up @@ -73,6 +74,14 @@ def validate(request):
return Response(request.data["title"])


def validate_list(request):
assert request.data == {
"title": "Hunky Dory",
"artists": ["Bowie", "Wowie"],
}
return Response(", ".join(request.data["artists"]))


def marshal(request):
"""
Returns JSON-serialized information about the album.
Expand Down Expand Up @@ -131,6 +140,14 @@ def config():
request_method=("GET", "POST"),
)

config.add_route("validate-list", "/validate-list")
config.add_view(
validate_list,
route_name="validate-list",
validate=AlbumSchema(),
request_method=("GET", "POST"),
)

# Marshaller
config.add_route("marshal", "/marshal")
config.add_view(
Expand Down
13 changes: 13 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ def test_get_validate_integration(app):
)


def test_get_validate_list_integration(app):
assert (
app.get(
"/validate-list",
{
"title": "Hunky Dory",
"artists": ["Bowie", "Wowie"],
},
).text
== "Bowie, Wowie"
)


def test_marshal_integration(app):
assert app.get("/marshal").json == {
"title": "Hunky Dory",
Expand Down

0 comments on commit 4cffd1f

Please sign in to comment.