From cb9c1037fdccb0bda8b6053d635afd5de9bba786 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Mon, 1 May 2017 15:39:05 +0430 Subject: [PATCH] added field filtering on serialization. --- TODO.md | 4 ++-- examples/extended_app.py | 3 +++ grest/utils.py | 4 ++++ tests/test_extended_app.py | 6 +++++- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/TODO.md b/TODO.md index 1cb2dea..d5e3535 100644 --- a/TODO.md +++ b/TODO.md @@ -4,5 +4,5 @@ [ ] Generalize use of API backend (So that it can use any ORM or OGM other than neomodel) [x] Fix __validation_rules__ property to use datatypes of the model (bind them together somehow!) [x] Include unit-tests -[ ] Include serialization filtering on fields (return only specified fields) -[ ] Add unit-tests for put, patch and delete verbs +[x] Include serialization filtering on fields (return only specified fields) +[x] Add unit-tests for put, patch and delete verbs diff --git a/examples/extended_app.py b/examples/extended_app.py index 4f89d45..58bfa1a 100644 --- a/examples/extended_app.py +++ b/examples/extended_app.py @@ -31,6 +31,8 @@ class Person(StructuredNode, utils.Node): last_name = StringProperty() phone_number = StringProperty(unique_index=True, required=True) + secret_field = StringProperty(default="secret", required=False) + pets = RelationshipTo(Pet, "HAS_PET") @@ -44,6 +46,7 @@ class PersonsView(GRest): "secondary": { "pets": "pet_id" }} + __filtered_fields__ = ["secret_field"] class PetsView(GRest): diff --git a/grest/utils.py b/grest/utils.py index f2fa8dc..b27675a 100644 --- a/grest/utils.py +++ b/grest/utils.py @@ -19,6 +19,7 @@ class Node(object): __validation_rules__ = {} + __filtered_fields__ = [] def __init__(self): super(self.__class__, self) @@ -29,6 +30,9 @@ def serialize(self): blocked_properties = ["id", "password", "current_otp", "validation_rules"] + if self.__filtered_fields__: + blocked_properties.extend(self.__filtered_fields__) + removable_keys = set() for prop in properties.keys(): # remove null key/values diff --git a/tests/test_extended_app.py b/tests/test_extended_app.py index ecb01f8..75f3c9c 100644 --- a/tests/test_extended_app.py +++ b/tests/test_extended_app.py @@ -125,13 +125,17 @@ def test_api_post_person(client): global uid res = client.post("/persons", data=json.dumps( - {"first_name": "test1", "last_name": "test2", "phone_number": "123"}), + {"first_name": "test1", "last_name": "test2", + "phone_number": "123", "secret_field": "MY_SECRET"}), headers={"Content-Type": "application/json"}) assert res.status_code == 200 if ("uid" in res.json): uid = res.json["uid"] assert "uid" in res.json + # check if `secret_field` is filtered + assert "secret_field" not in res.json + # post existing person res = client.post("/persons", data=json.dumps(