Skip to content

Commit

Permalink
Merge pull request #100 from mjreiss/skip-nones
Browse files Browse the repository at this point in the history
Option to skip response fields where value is None
  • Loading branch information
apryor6 authored Mar 16, 2021
2 parents 945f82b + dc1db5d commit 38824c4
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
16 changes: 16 additions & 0 deletions flask_accepts/decorators/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ def responds(
validate: bool = False,
description: str = None,
use_swagger: bool = True,
skip_none: bool = False,
):
"""
Serialize the output of a function using the Marshmallow schema to dump the results.
Expand Down Expand Up @@ -285,6 +286,21 @@ def inner(*args, **kwargs):
if envelope:
serialized = OrderedDict([(envelope, serialized)]) if ordered else {envelope: serialized}

if skip_none:
def remove_none(obj):
if isinstance(obj, list):
return [remove_none(entry) for entry in obj if entry is not None]
if isinstance(obj, dict):
result = {}
for key, value in obj.items():
value = remove_none(value)
if key is not None and value is not None:
result[key] = value
return result
return obj

serialized = remove_none(serialized)

if not _is_method(func):
# Regular route, need to manually create Response
return jsonify(serialized), status_code
Expand Down
43 changes: 43 additions & 0 deletions flask_accepts/decorators/decorators_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,49 @@ def get(self):
assert resp.status_code == 200
assert resp.json == {'test-data': {'_id': 42, 'name': 'Jon Snow'}}


def test_responds_skips_none_false(app, client):
class TestSchema(Schema):
_id = fields.Integer()
name = fields.String()

api = Api(app)

@api.route("/test")
class TestResource(Resource):
@responds(schema=TestSchema, api=api)
def get(self):
return {"_id": 42, "name": None}

with client as cl:
resp = cl.get("/test")
assert resp.status_code == 200
assert resp.json == {'_id': 42, 'name': None}


def test_responds_with_nested_skips_none_true(app, client):
class NestSchema(Schema):
_id = fields.Integer()
name = fields.String()

class TestSchema(Schema):
name = fields.String()
child = fields.Nested(NestSchema)

api = Api(app)

@api.route("/test")
class TestResource(Resource):
@responds(schema=TestSchema, api=api, skip_none=True, many=True)
def get(self):
return [{"name": None, "child": {"_id": 42, "name": None}}]

with client as cl:
resp = cl.get("/test")
assert resp.status_code == 200
assert resp.json == [{"child": {'_id': 42}}]


def test_accepts_with_nested_schema(app, client): # noqa
class TestSchema(Schema):
_id = fields.Integer()
Expand Down

0 comments on commit 38824c4

Please sign in to comment.