Esempio n. 1
0
    def retrieve_list(self, session, filters, *args, **kwargs):
        """
        Retrieves a list of the model for this manager.
        It is restricted by the filters provided.

        :param Session session: The SQLAlchemy session to use
        :param dict filters: The filters to restrict the returned
            models on
        :return: A tuple of the list of dictionary representation
            of the models and the dictionary of meta data
        :rtype: list, dict
        """
        query = self.queryset(session)
        translator = IntegerField('tmp')
        pagination_count = translator.translate(
            filters.pop(self.pagination_count_query_arg, self.paginate_by))
        pagination_pk = translator.translate(
            filters.pop(self.pagination_pk_query_arg, 1))
        pagination_pk -= 1  # logic works zero based. Pagination shouldn't be though

        query = query.filter_by(**filters)

        if pagination_pk:
            query = query.offset(pagination_pk * pagination_count)
        if pagination_count:
            query = query.limit(pagination_count + 1)

        count = query.count()
        next_link = None
        previous_link = None
        if count > pagination_count:
            next_link = {
                self.pagination_pk_query_arg: pagination_pk + 2,
                self.pagination_count_query_arg: pagination_count
            }
        if pagination_pk > 0:
            previous_link = {
                self.pagination_pk_query_arg: pagination_pk,
                self.pagination_count_query_arg: pagination_count
            }

        field_dict = self.dot_field_list_to_dict(self.list_fields)
        props = self.serialize_model(query[:pagination_count],
                                     field_dict=field_dict)
        meta = dict(links=dict(next=next_link, previous=previous_link))
        return props, meta
Esempio n. 2
0
class CreateCommentMixin(object):
    @translate(fields=[IntegerField('id', required=True)], validate=True)
    @apimethod(route='/create_comment/', methods=['POST'])
    def create_comment(cls, request):
        args = request.body_args
        args['post_id'] = request.get('id')
        request.body_args = args
        CommentResource.create(request)
        return cls.retrieve(request)
Esempio n. 3
0
    def test_translate_keeps_undefined_fields(self):
        """
        Tests that any fields not in the defined dictionary
        are still included.
        """
        field_dict = [StringField('field1'), IntegerField('field2')]
        field = DictField('f', required=True, field_list=field_dict)

        input_vals = dict(field1='hey', field2='5', field3='Who Cares?')
        resp = field.translate(input_vals, validate=True)
        self.assertIn('field3', resp)
Esempio n. 4
0
    def test_translate_success(self):
        """
        Tests the expected conditions for
        the translate method.
        """
        field_dict = [StringField('field1'), IntegerField('field2')]
        field = DictField('f', required=True, field_list=field_dict)

        input_vals = dict(field1='hey', field2='5')
        resp = field.translate(input_vals, validate=True)
        self.assertDictEqual(dict(field1='hey', field2=5), resp)
Esempio n. 5
0
 def test_validate_items(self):
     """
     Tests validating the items in the list
     """
     items = [10, 15]
     l = ListField('field', indv_field=IntegerField('int', minimum=5))
     resp_items = l.translate(items, validate=True)
     self.assertEqual(items, resp_items)
     items = [15, 0]
     self.assertRaises(ValidationException,
                       l.translate,
                       items,
                       validate=True)
class GroupManager(AlchemyManager):
    model = Group
    fields = ('id', 'name', 'users.id', 'users.username', 'users.first_name')
    create_fields = ('name', )
    update_fields = tuple()
    list_fields = (
        'id',
        'name',
    )
    _field_validators = {
        'name': StringField('name', minimum=3, maximum=20),
        'id': IntegerField('id')
    }
class PostResource(restmixins.CRUDL):
    append_slash = True
    pks = ('id', )
    manager = PostManager(session_handler)
    resource_name = 'post'
    _relationships = (ListRelationship('comments',
                                       relation='CommentResource'), )

    @translate(fields=[IntegerField('id', required=True)], validate=True)
    @apimethod(route='/create_comment/', methods=['POST'])
    def create_comment(cls, request):
        args = request.body_args
        args['post_id'] = request.get('id')
        request.body_args = args
        CommentResource.create(request)
        return cls.retrieve(request)
Esempio n. 8
0
class ItemManager(BaseManager):
    """Manager that interops between ripozo and grpc.

    Provides convience functions primarily for basic CRUD.
    """
    fields = (
        'id',
        'name',
    )
    field_validators = [
        IntegerField('id', required=True),
        StringField('name', required=True),
    ]

    def create(self, values, *args, **kwargs):
        raise NotImplementedError()

    def delete(self, lookup_keys, *args, **kwargs):
        raise NotImplementedError()

    def retrieve(self, lookup_keys, *args, **kwargs):
        """Retrieve a single item and nothing more as a dictionary.

        Args:
            lookup_keys (dict): Taken from url_params on flask request. Used to
                lookup a item and its associated values.

        Returns:
            dict or None: Properties of the retrieved item or None if no
                such item found.
        """
        resp = items_conn.stub.GetItem(
            items_pb2.GetItemRequest(id=lookup_keys['id']))
        item = resp.item

        if item:
            return dict(id=item.id, name=item.name)

    def retrieve_list(self, filters, *args, **kwargs):
        raise NotImplementedError()

    def update(self, lookup_keys, updates, *args, **kwargs):
        raise NotImplementedError()
Esempio n. 9
0
    def test_translate_subfield_failure(self):
        """
        Tests that when one of the child fields
        fails then this field as a whole will fail.
        """
        field_dict = [
            StringField('field1'),
            IntegerField('field2', maximum=10)
        ]
        field = DictField('f', required=True, field_list=field_dict)

        input_vals = dict(field1='hey', field2='notanumber')
        self.assertRaises(TranslationException,
                          field.translate,
                          input_vals,
                          validate=True)

        input_vals = dict(field1='hey', field2='11')
        self.assertRaises(ValidationException,
                          field.translate,
                          input_vals,
                          validate=True)
Esempio n. 10
0
 class TranslateClass2(ResourceBase):
     @apimethod(methods=['GET'])
     @translate(fields=[IntegerField('id', required=True)],
                validate=False)
     def hey(cls, req):
         return req.body_args.get('id')