コード例 #1
0
 def test_links_last_page(self, app):
     with app.test_request_context('/examples/?page[size]=10&page[number]=1'):
         links = query_string.SizeNumberPagination().get_links(
             page_size=10, current_page=5, total_count=50)
         assert links == {
             'self': 'http://localhost/examples/?page[size]=10&page[number]=5',
             'first': 'http://localhost/examples/?page[size]=10&page[number]=1',
             'previous': 'http://localhost/examples/?page[size]=10&page[number]=4',
             'next': None,
             'last': 'http://localhost/examples/?page[size]=10&page[number]=5'
         }
コード例 #2
0
 def test_pagination_not_int(self, app):
     with app.test_request_context('/examples/?page[size]=100&page[number]=x'):
         with pytest.raises(exceptions.InvalidPage):
             query_string.SizeNumberPagination().parse()
             pytest.fail('Page parameters must be integers.')
コード例 #3
0
 def test_pagination_invalid_provided(self, app):
     with app.test_request_context('/examples/?page[size]=100'):
         with pytest.raises(exceptions.InvalidPage):
             query_string.SizeNumberPagination().parse()
             pytest.fail('One of page parameters wrongly or not specified.')
コード例 #4
0
 def test_pagination_not_provided(self, app):
     with app.test_request_context('/examples/'):
         parsed_pagination = query_string.SizeNumberPagination().parse()
         assert parsed_pagination == {}
コード例 #5
0
 def test_pagination(self, app):
     with app.test_request_context('/examples/?page[size]=100&page[number]=50'):
         parsed_pagination = query_string.SizeNumberPagination().parse()
         assert parsed_pagination == {'size': 100, 'number': 50}
コード例 #6
0
ファイル: resources.py プロジェクト: maruqu/flask-jsonapi
class ResourceList(ResourceBase):
    methods = ['GET', 'POST']
    filter_schema = filters_schema.FilterSchema()
    pagination = query_string.SizeNumberPagination()

    def __init__(self, *, filter_schema=None, **kwargs):
        super().__init__(**kwargs)
        if filter_schema:
            self.filter_schema = filter_schema

    def get(self, *args, **kwargs):
        parsed_filters = self.filter_schema.parse()
        parsed_pagination = self.pagination.parse()
        objects_list = self.read_many(filters=parsed_filters,
                                      pagination=parsed_pagination)
        include_fields = self.include_parser.parse()
        sparse_fields = self.sparse_fields_parser.parse()
        try:
            objects, errors = self.schema(
                many=True, include_data=include_fields,
                only=sparse_fields).dump(objects_list)
        except marshmallow.ValidationError as e:
            return response.JsonApiErrorResponse.from_marshmallow_errors(
                e.messages)
        except (AttributeError, KeyError, ValueError) as e:
            logger.error('Error Processing Request',
                         extra={
                             'status_code': http.HTTPStatus.BAD_REQUEST,
                             'request': request,
                             'exception': e
                         })
            return helpers.make_response('Error Processing Request',
                                         http.HTTPStatus.BAD_REQUEST)
        else:
            if errors:
                return response.JsonApiErrorResponse.from_marshmallow_errors(
                    errors)
            else:
                pagination_links = self.get_pagination_links(
                    parsed_pagination, parsed_filters)
                return response.JsonApiListResponse(
                    response_data=objects,
                    links=pagination_links,
                )

    def get_pagination_links(self, parsed_pagination, parsed_filters):
        if parsed_pagination:
            page_size = parsed_pagination['size']
            current_page = parsed_pagination['number']
            total_count = self.get_count(filters=parsed_filters)
            pagination_links = self.pagination.get_links(
                page_size, current_page, total_count)
        else:
            pagination_links = {}
        return pagination_links

    def post(self, *args, **kwargs):
        try:
            data, errors = self.schema().load(request.get_json())
        except marshmallow_jsonapi_exceptions.IncorrectTypeError as e:
            return response.JsonApiErrorResponse.from_marshmallow_errors(
                e.messages)
        except marshmallow.ValidationError as e:
            return response.JsonApiErrorResponse.from_marshmallow_errors(
                e.messages)
        else:
            if errors:
                response.JsonApiErrorResponse.from_marshmallow_errors(errors)
            else:
                return self.prepare_response(data)

    def prepare_response(self, data):
        object = self.create(data=data)
        return response.JsonApiResponse(
            self.schema().dump(object).data,
            status=http.HTTPStatus.CREATED,
        )

    def read_many(self, filters, pagination):
        raise NotImplementedError

    def get_count(self, filters):
        raise NotImplementedError

    def create(self, data, **kwargs):
        raise NotImplementedError