From ae6cc6ffa39a5c3bfeda50394abf7c915e4c33db Mon Sep 17 00:00:00 2001 From: Luis Orduz Date: Mon, 16 Jul 2018 16:48:25 -0500 Subject: [PATCH 1/6] Enabling sort_attribute --- docs/resources.rst | 4 --- flask_potion/resource.py | 31 +++++++++++++++-- tests/test_model_resource.py | 66 ++++++++++++++++++++++++++++++------ 3 files changed, 85 insertions(+), 16 deletions(-) diff --git a/docs/resources.rst b/docs/resources.rst index a59c988..b769794 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -19,10 +19,6 @@ for the resource. :class:`ModelResource` is written for create, read, update, delete actions on collections of items matching the resource schema. -A data store connection is maintained by a :class:`manager.Manager` instance. -The manager class can be specified in ``Meta.manager``; if no manager is specified, ``Api.default_manager`` is used. -Managers are configured through attributes in ``Meta``. Most managers expect a *model* to be defined under ``Meta.model``. - .. autoclass:: ModelResource :members: diff --git a/flask_potion/resource.py b/flask_potion/resource.py index c0cff3d..5b8b685 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -212,11 +212,37 @@ def __new__(mcs, name, bases, members): if 'model' in changes or 'model' in meta and 'manager' in changes: if meta.manager is not None: class_.manager = meta.manager(class_, meta.model) + + if meta.get('sort_attribute'): + try: + field, reverse = meta.sort_attribute + except ValueError: + field, reverse = meta.sort_attribute, False + + if field not in class_.schema.fields: + meta.sort_attribute = None + else: + meta.sort_attribute = ( + (class_.schema.fields[field], field, reverse), + ) + return class_ class ModelResource(six.with_metaclass(ModelResourceMeta, Resource)): """ + :class:`Meta` class attributes: + + ===================== ============================== ============================================================================== + Attribute name Default Description + ===================== ============================== ============================================================================== + manager ``Api.default_manager`` A data store connection is maintained by a :class:`manager.Manager` instance. + Managers are configured through attributes in ``Meta``. Most managers expect + a *model* to be defined under ``Meta.model``. + sort_attribute None The field used to sort the list in the `instances` endpoint. Can be the + field name as ``string`` or a ``tuple`` with the field name and a boolean + for ``reverse`` (defaults to ``False``). + ===================== ============================== ============================================================================== .. method:: create @@ -261,8 +287,9 @@ class ModelResource(six.with_metaclass(ModelResourceMeta, Resource)): manager = None @Route.GET('', rel="instances") - def instances(self, **kwargs): - return self.manager.paginated_instances(**kwargs) + def instances(self, sort=None, **kwargs): + sort = sort or self.meta.sort_attribute + return self.manager.paginated_instances(sort=sort, **kwargs) # TODO custom schema (Instances/Instances) that contains the necessary schema. instances.request_schema = instances.response_schema = Instances() # TODO NOTE Instances('self') for filter, etc. schema diff --git a/tests/test_model_resource.py b/tests/test_model_resource.py index a741346..ac4d6ce 100644 --- a/tests/test_model_resource.py +++ b/tests/test_model_resource.py @@ -3,6 +3,19 @@ from tests import BaseTestCase +def TestResource(res_name, sort=None): + class NewResource(ModelResource): + class Schema: + name = fields.String() + secret = fields.String(io="c") + slug = fields.String(io="cr") + class Meta: + name = res_name + sort_attribute = sort + + return NewResource + + class ModelResourceTestCase(BaseTestCase): def setUp(self): @@ -10,16 +23,7 @@ def setUp(self): self.api = Api(self.app, default_manager=MemoryManager) def test_schema_io(self): - - class FooResource(ModelResource): - class Schema: - name = fields.String() - secret = fields.String(io="c") - slug = fields.String(io="cr") - - class Meta: - name = "foo" - + FooResource = TestResource("foo") self.api.add_resource(FooResource) response = self.client.post("/foo", data={ @@ -67,3 +71,45 @@ class Meta: "slug": "foo", "secret": "mystery" }, FooResource.manager.items[1]) + + + def test_sort_attribute(self): + DescResource = TestResource("desc", sort=("name", True)) + AscResource = TestResource("asc", sort="name") + UnsortedResource = TestResource("unsorted") + + self.api.add_resource(DescResource) + self.api.add_resource(AscResource) + self.api.add_resource(UnsortedResource) + + first_data = { + "name": "Foo", + "secret": "mystery", + "slug": "foo" + } + second_data = { + "name": "Bar", + "secret": "mystery", + "slug": "bar" + } + + self.client.post("/asc", data=first_data) + self.client.post("/asc", data=second_data) + self.client.post("/desc", data=first_data) + self.client.post("/desc", data=second_data) + self.client.post("/unsorted", data=first_data) + self.client.post("/unsorted", data=second_data) + + response = self.client.get("/desc").json + + self.assertEqual(response[0]['name'], "Foo") + self.assertEqual(response[1]['name'], "Bar") + + response = self.client.get("/asc").json + self.assertEqual(response[0]['name'], "Bar") + self.assertEqual(response[1]['name'], "Foo") + + response = self.client.get("/unsorted").json + + self.assertEqual(response[0]['name'], "Foo") + self.assertEqual(response[1]['name'], "Bar") From 0a73612d5c36c10604dbdea4f0e2f7f03c20498b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20Sch=C3=B6ning?= Date: Mon, 3 Dec 2018 11:23:03 +0100 Subject: [PATCH 2/6] Revert "Use sort_attribute as default sort for instances, support DESC sorting (#152)" This reverts commit 66f11dcc62d53f9a8b61e23ffcd7c3a8ce4c431a. --- docs/resources.rst | 4 + flask_potion/contrib/alchemy/manager.py | 18 +---- flask_potion/resource.py | 19 +---- .../alchemy/test_manager_sqlalchemy.py | 75 ------------------- 4 files changed, 7 insertions(+), 109 deletions(-) diff --git a/docs/resources.rst b/docs/resources.rst index b769794..a59c988 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -19,6 +19,10 @@ for the resource. :class:`ModelResource` is written for create, read, update, delete actions on collections of items matching the resource schema. +A data store connection is maintained by a :class:`manager.Manager` instance. +The manager class can be specified in ``Meta.manager``; if no manager is specified, ``Api.default_manager`` is used. +Managers are configured through attributes in ``Meta``. Most managers expect a *model* to be defined under ``Meta.model``. + .. autoclass:: ModelResource :members: diff --git a/flask_potion/contrib/alchemy/manager.py b/flask_potion/contrib/alchemy/manager.py index 0c09eb8..867e90d 100644 --- a/flask_potion/contrib/alchemy/manager.py +++ b/flask_potion/contrib/alchemy/manager.py @@ -45,8 +45,7 @@ def _init_model(self, resource, model, meta): self.id_attribute = mapper.primary_key[0].name self.id_field = self._get_field_from_column_type(self.id_column, self.id_attribute, io="r") - self.default_sort_expression = self._get_sort_expression( - model, meta, self.id_column) + self.default_sort_expression = self.id_column.asc() fs = resource.schema if meta.include_id: @@ -87,14 +86,6 @@ def _init_model(self, resource, model, meta): fs.required.add(name) fs.set(name, self._get_field_from_column_type(column, name, io=io)) - def _get_sort_expression(self, model, meta, id_column): - if meta.sort_attribute is None: - return id_column.asc() - - attr_name, reverse = meta.sort_attribute - attr = getattr(model, attr_name) - return attr.desc() if reverse else attr.asc() - def _get_field_from_column_type(self, column, attribute, io="rw"): args = () kwargs = {} @@ -204,12 +195,7 @@ def _query_order_by(self, query, sort=None): if isinstance(field, fields.ToOne): target_alias = aliased(field.target.meta.model) query = query.outerjoin(target_alias, column).reset_joinpoint() - sort_attribute = None - if field.target.meta.sort_attribute: - sort_attribute, _ = field.target.meta.sort_attribute - column = getattr( - target_alias, - sort_attribute or field.target.manager.id_attribute) + column = getattr(target_alias, field.target.meta.sort_attribute or field.target.manager.id_attribute) order_clauses.append(column.desc() if reverse else column.asc()) diff --git a/flask_potion/resource.py b/flask_potion/resource.py index 5ce8f95..c0cff3d 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -212,28 +212,11 @@ def __new__(mcs, name, bases, members): if 'model' in changes or 'model' in meta and 'manager' in changes: if meta.manager is not None: class_.manager = meta.manager(class_, meta.model) - - sort_attribute = meta.get('sort_attribute') - if sort_attribute is not None and isinstance(sort_attribute, str): - meta.sort_attribute = sort_attribute, False - return class_ class ModelResource(six.with_metaclass(ModelResourceMeta, Resource)): """ - :class:`Meta` class attributes: - - ===================== ============================== ============================================================================== - Attribute name Default Description - ===================== ============================== ============================================================================== - manager ``Api.default_manager`` A data store connection is maintained by a :class:`manager.Manager` instance. - Managers are configured through attributes in ``Meta``. Most managers expect - a *model* to be defined under ``Meta.model``. - sort_attribute None The field used to sort the list in the `instances` endpoint. Can be the - field name as ``string`` or a ``tuple`` with the field name and a boolean - for ``reverse`` (defaults to ``False``). - ===================== ============================== ============================================================================== .. method:: create @@ -339,4 +322,4 @@ class Meta: RefKey(), IDKey() ) - natural_key = None + natural_key = None \ No newline at end of file diff --git a/tests/contrib/alchemy/test_manager_sqlalchemy.py b/tests/contrib/alchemy/test_manager_sqlalchemy.py index df55fb0..57c4287 100644 --- a/tests/contrib/alchemy/test_manager_sqlalchemy.py +++ b/tests/contrib/alchemy/test_manager_sqlalchemy.py @@ -448,78 +448,3 @@ class Meta: "$id": 1, "username": "foo" }, response.json) - - -class SQLAlchemySortTestCase(BaseTestCase): - - def setUp(self): - super(SQLAlchemySortTestCase, self).setUp() - self.app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' - self.api = Api(self.app) - self.sa = sa = SQLAlchemy( - self.app, session_options={"autoflush": False}) - - class Type(sa.Model): - id = sa.Column(sa.Integer, primary_key=True) - name = sa.Column(sa.String(60), nullable=False) - - class Machine(sa.Model): - id = sa.Column(sa.Integer, primary_key=True) - name = sa.Column(sa.String(60), nullable=False) - - type_id = sa.Column(sa.Integer, sa.ForeignKey(Type.id)) - type = sa.relationship(Type, foreign_keys=[type_id]) - - sa.create_all() - - class MachineResource(ModelResource): - class Meta: - model = Machine - - class Schema: - type = fields.ToOne('type') - - class TypeResource(ModelResource): - class Meta: - model = Type - sort_attribute = ('name', True) - - self.MachineResource = MachineResource - self.TypeResource = TypeResource - - self.api.add_resource(MachineResource) - self.api.add_resource(TypeResource) - - def test_default_sorting_with_desc(self): - self.client.post('/type', data={"name": "aaa"}) - self.client.post('/type', data={"name": "ccc"}) - self.client.post('/type', data={"name": "bbb"}) - response = self.client.get('/type') - self.assert200(response) - self.assertJSONEqual( - [{'$uri': '/type/2', 'name': 'ccc'}, - {'$uri': '/type/3', 'name': 'bbb'}, - {'$uri': '/type/1', 'name': 'aaa'}], - response.json) - - def test_sort_by_related_field(self): - response = self.client.post('/type', data={"name": "aaa"}) - self.assert200(response) - aaa_uri = response.json["$uri"] - response = self.client.post('/type', data={"name": "bbb"}) - self.assert200(response) - bbb_uri = response.json["$uri"] - self.client.post( - '/machine', data={"name": "foo", "type": {"$ref": aaa_uri}}) - self.assert200(response) - self.client.post( - '/machine', data={"name": "bar", "type": {"$ref": bbb_uri}}) - self.assert200(response) - response = self.client.get('/machine?sort={"type": true}') - self.assert200(response) - type_uris = [entry['type']['$ref'] for entry in response.json] - self.assertTrue(type_uris, [bbb_uri, aaa_uri]) - response = self.client.get('/machine?sort={"type": false}') - self.assert200(response) - type_uris = [entry['type']['$ref'] for entry in response.json] - self.assertTrue(type_uris, [bbb_uri, aaa_uri]) From bbe7b2587ec0e17a9ce56fd0482332fef6a89bc5 Mon Sep 17 00:00:00 2001 From: Luis Orduz Date: Thu, 6 Dec 2018 17:59:36 -0500 Subject: [PATCH 3/6] Resolving conflicts and fixing something that nose was causing --- flask_potion/contrib/memory/manager.py | 2 +- flask_potion/resource.py | 9 ++++++++- tests/test_model_resource.py | 10 +++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/flask_potion/contrib/memory/manager.py b/flask_potion/contrib/memory/manager.py index 9219b16..6145519 100644 --- a/flask_potion/contrib/memory/manager.py +++ b/flask_potion/contrib/memory/manager.py @@ -33,7 +33,7 @@ def _filter_items(items, conditions): @staticmethod def _sort_items(items, sort): - for field, key, reverse in reversed(sort): + for field, key, reverse in (sort,): items = sorted(items, key=lambda item: get_value(key, item, None), reverse=reverse) return items diff --git a/flask_potion/resource.py b/flask_potion/resource.py index fb074f7..c951e4f 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -215,7 +215,14 @@ def __new__(mcs, name, bases, members): sort_attribute = meta.get('sort_attribute') if sort_attribute is not None and isinstance(sort_attribute, str): - meta.sort_attribute = sort_attribute, False + sort_attribute = sort_attribute, False + if sort_attribute and sort_attribute[0] in class_.schema.fields: + field, reverse = sort_attribute + meta.sort_attribute = ( + (class_.schema.fields[field], field, reverse) + ) + else: + meta.sort_attribute = None return class_ diff --git a/tests/test_model_resource.py b/tests/test_model_resource.py index cbd7cd6..4e265e0 100644 --- a/tests/test_model_resource.py +++ b/tests/test_model_resource.py @@ -3,7 +3,7 @@ from tests import BaseTestCase -def TestResource(res_name, sort=None): +def DummyResource(res_name, sort=None): class NewResource(ModelResource): class Schema: name = fields.String() @@ -23,7 +23,7 @@ def setUp(self): self.api = Api(self.app, default_manager=MemoryManager) def test_schema_io(self): - FooResource = TestResource("foo") + FooResource = DummyResource("foo") self.api.add_resource(FooResource) response = self.client.post("/foo", data={ @@ -73,9 +73,9 @@ def test_schema_io(self): }, FooResource.manager.items[1]) def test_sort_attribute(self): - DescResource = TestResource("desc", sort=("name", True)) - AscResource = TestResource("asc", sort="name") - UnsortedResource = TestResource("unsorted") + DescResource = DummyResource("desc", sort=("name", True)) + AscResource = DummyResource("asc", sort="name") + UnsortedResource = DummyResource("unsorted") self.api.add_resource(DescResource) self.api.add_resource(AscResource) From 964358f01d1f01dfbce9566caacb830cc5c520ae Mon Sep 17 00:00:00 2001 From: Luis Orduz Date: Thu, 6 Dec 2018 18:52:35 -0500 Subject: [PATCH 4/6] The docs got overwritten --- docs/resources.rst | 4 ---- flask_potion/resource.py | 12 ++++++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/resources.rst b/docs/resources.rst index a59c988..b769794 100644 --- a/docs/resources.rst +++ b/docs/resources.rst @@ -19,10 +19,6 @@ for the resource. :class:`ModelResource` is written for create, read, update, delete actions on collections of items matching the resource schema. -A data store connection is maintained by a :class:`manager.Manager` instance. -The manager class can be specified in ``Meta.manager``; if no manager is specified, ``Api.default_manager`` is used. -Managers are configured through attributes in ``Meta``. Most managers expect a *model* to be defined under ``Meta.model``. - .. autoclass:: ModelResource :members: diff --git a/flask_potion/resource.py b/flask_potion/resource.py index 0c0536e..a6bb0be 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -229,6 +229,18 @@ def __new__(mcs, name, bases, members): class ModelResource(six.with_metaclass(ModelResourceMeta, Resource)): """ + :class:`Meta` class attributes: + + ===================== ============================== ============================================================================== + Attribute name Default Description + ===================== ============================== ============================================================================== + manager ``Api.default_manager`` A data store connection is maintained by a :class:`manager.Manager` instance. + Managers are configured through attributes in ``Meta``. Most managers expect + a *model* to be defined under ``Meta.model``. + sort_attribute None The field used to sort the list in the `instances` endpoint. Can be the + field name as ``string`` or a ``tuple`` with the field name and a boolean + for ``reverse`` (defaults to ``False``). + ===================== ============================== ============================================================================== .. method:: create From 4c5ab2c6d9bf86d0de9ab2fd6675a1a2d5a9a2cc Mon Sep 17 00:00:00 2001 From: Luis Orduz Date: Thu, 6 Dec 2018 18:53:35 -0500 Subject: [PATCH 5/6] newline --- flask_potion/resource.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flask_potion/resource.py b/flask_potion/resource.py index a6bb0be..c951e4f 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -347,4 +347,4 @@ class Meta: RefKey(), IDKey() ) - natural_key = None \ No newline at end of file + natural_key = None From 22a5d64f8692ad841fd42dd1230563b7c8115457 Mon Sep 17 00:00:00 2001 From: Luis Orduz Date: Thu, 6 Dec 2018 19:14:19 -0500 Subject: [PATCH 6/6] Fixed consistency --- flask_potion/contrib/memory/manager.py | 2 +- flask_potion/resource.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/flask_potion/contrib/memory/manager.py b/flask_potion/contrib/memory/manager.py index 6145519..3e97fe1 100644 --- a/flask_potion/contrib/memory/manager.py +++ b/flask_potion/contrib/memory/manager.py @@ -33,7 +33,7 @@ def _filter_items(items, conditions): @staticmethod def _sort_items(items, sort): - for field, key, reverse in (sort,): + for field, key, reverse in sort: items = sorted(items, key=lambda item: get_value(key, item, None), reverse=reverse) return items diff --git a/flask_potion/resource.py b/flask_potion/resource.py index c951e4f..51eda15 100644 --- a/flask_potion/resource.py +++ b/flask_potion/resource.py @@ -219,7 +219,7 @@ def __new__(mcs, name, bases, members): if sort_attribute and sort_attribute[0] in class_.schema.fields: field, reverse = sort_attribute meta.sort_attribute = ( - (class_.schema.fields[field], field, reverse) + (class_.schema.fields[field], field, reverse), ) else: meta.sort_attribute = None