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/contrib/memory/manager.py b/flask_potion/contrib/memory/manager.py index 9219b16..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 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 5ce8f95..51eda15 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_ @@ -278,8 +285,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/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]) diff --git a/tests/test_model_resource.py b/tests/test_model_resource.py index 4e920fd..4e265e0 100644 --- a/tests/test_model_resource.py +++ b/tests/test_model_resource.py @@ -3,6 +3,19 @@ from tests import BaseTestCase +def DummyResource(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 = DummyResource("foo") self.api.add_resource(FooResource) response = self.client.post("/foo", data={ @@ -68,6 +72,47 @@ class Meta: "secret": "mystery" }, FooResource.manager.items[1]) + def test_sort_attribute(self): + DescResource = DummyResource("desc", sort=("name", True)) + AscResource = DummyResource("asc", sort="name") + UnsortedResource = DummyResource("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") + def test_inline_schema(self): class FooResource(ModelResource): class Meta: