def select_parser(self, parsers):
        """
        Determine which parser to use for parsing the request body.
        Returns a two-tuple of (parser, content type).
        """
        content_type_header = request.content_type

        client_media_type = MediaType(content_type_header)
        for parser in parsers:
            server_media_type = MediaType(parser.media_type)
            if server_media_type.satisfies(client_media_type):
                return (parser, client_media_type)

        raise exceptions.UnsupportedMediaType()
Exemple #2
0
    def select_parser(self, parsers):
        """
        Determine which parser to use for parsing the request body.
        Returns a two-tuple of (parser, content type).
        """
        content_type_header = request.content_type

        client_media_type = MediaType(content_type_header)
        for parser in parsers:
            server_media_type = MediaType(parser.media_type)
            if server_media_type.satisfies(client_media_type):
                return (parser, client_media_type)

        raise exceptions.UnsupportedMediaType()
    def test_parse_complex_accept_header(self):
        """
        The accept header should be parsed into a list of sets of MediaType.
        The list is an ordering of precedence.

        Note that we disregard 'q' values when determining precedence, and
        instead differentiate equal values by using the server preference.
        """
        header = 'application/xml; schema=foo, application/json; q=0.9, application/xml, */*'
        parsed = parse_accept_header(header)
        assert parsed == [
            set([MediaType('application/xml; schema=foo')]),
            set([MediaType('application/json; q=0.9'), MediaType('application/xml')]),
            set([MediaType('*/*')]),
        ]
Exemple #4
0
 def test_parse_complex_accept_header(self):
     """
     The accept header should be parsed into a list of sets of MediaType.
     The list is an ordering of precedence and sublists are in the order
     of quality.
     """
     header = 'application/xml; schema=foo, application/json; q=0.9, application/xml, */*'
     parsed = parse_accept_header(header)
     self.assertEqual(parsed, [
         [MediaType('application/xml; schema=foo')],
         [
             MediaType('application/xml'),
             MediaType('application/json; q=0.9')
         ],
         [MediaType('*/*')],
     ])
Exemple #5
0
 def test_media_type_with_wildcard_main_type(self):
     media = MediaType('*/*')
     self.assertEqual(str(media), '*/*')
     self.assertEqual(media.main_type, '*')
     self.assertEqual(media.sub_type, '*')
     self.assertEqual(media.full_type, '*/*')
     self.assertEqual(media.params, {})
     self.assertEqual(media.precedence, 0)
Exemple #6
0
 def test_media_type_without_params(self):
     media = MediaType('application/xml')
     self.assertEqual(str(media), 'application/xml')
     self.assertEqual(media.main_type, 'application')
     self.assertEqual(media.sub_type, 'xml')
     self.assertEqual(media.full_type, 'application/xml')
     self.assertEqual(media.params, {})
     self.assertEqual(media.precedence, 2)
Exemple #7
0
 def test_media_type_with_q_params(self):
     media = MediaType('application/xml; q=0.5')
     self.assertEqual(str(media), 'application/xml; q="0.5"')
     self.assertEqual(media.main_type, 'application')
     self.assertEqual(media.sub_type, 'xml')
     self.assertEqual(media.full_type, 'application/xml')
     self.assertEqual(media.params, {'q': '0.5'})
     self.assertEqual(media.precedence, 2)
Exemple #8
0
 def test_render_json_with_indent(self):
     app = self._make_app()
     renderer = renderers.JSONRenderer()
     with app.app_context():
         content = renderer.render({'example': 'example'},
                                   MediaType('application/json; indent=4'))
     expected = '{\n    "example": "example"\n}'
     self.assertEqual(content, expected)
 def test_media_type_with_wildcard_main_type(self):
     media = MediaType('*/*')
     assert str(media) == '*/*'
     assert media.main_type == '*'
     assert media.sub_type == '*'
     assert media.full_type == '*/*'
     assert media.params == {}
     assert media.precedence == 0
 def test_media_type_without_params(self):
     media = MediaType('application/xml')
     assert str(media) == 'application/xml'
     assert media.main_type == 'application'
     assert media.sub_type == 'xml'
     assert media.full_type == 'application/xml'
     assert media.params == {}
     assert media.precedence == 2
 def test_media_type_with_q_params(self):
     media = MediaType('application/xml; q=0.5')
     assert str(media) == 'application/xml; q="0.5"'
     assert media.main_type == 'application'
     assert media.sub_type == 'xml'
     assert media.full_type == 'application/xml'
     assert media.params == {'q': '0.5'}
     assert media.precedence == 2
 def test_media_type_with_params(self):
     media = MediaType('application/xml; schema=foobar, q=0.5')
     assert str(media) == 'application/xml; q="0.5", schema="foobar"'
     assert media.main_type == 'application'
     assert media.sub_type == 'xml'
     assert media.full_type == 'application/xml'
     assert media.params == {'schema': 'foobar', 'q': '0.5'}
     assert media.precedence == 3
     assert repr(media) == '<MediaType \'application/xml; q="0.5", schema="foobar"\'>'
Exemple #13
0
 def test_media_type_with_params(self):
     media = MediaType('application/xml; schema=foobar, q=0.5')
     self.assertEqual(str(media),
                      'application/xml; q="0.5", schema="foobar"')
     self.assertEqual(media.main_type, 'application')
     self.assertEqual(media.sub_type, 'xml')
     self.assertEqual(media.full_type, 'application/xml')
     self.assertEqual(media.params, {'schema': 'foobar', 'q': '0.5'})
     self.assertEqual(media.precedence, 3)
     self.assertEqual(
         repr(media),
         '<MediaType \'application/xml; q="0.5", schema="foobar"\'>')
Exemple #14
0
    def test_render_json_with_custom_encoder(self):
        class CustomJsonEncoder(JSONEncoder):
            def default(self, o):
                if isinstance(o, datetime):
                    return o.isoformat()
                return super(CustomJsonEncoder, self).default(o)

        app = self._make_app()
        app.json_encoder = CustomJsonEncoder
        renderer = renderers.JSONRenderer()
        date = datetime(2017, 10, 5, 15, 22)
        with app.app_context():
            content = renderer.render(date, MediaType('application/json'))
Exemple #15
0
    def render(self, data, media_type, **options):
        # Render the content as it would have been if the client
        # had requested 'Accept: */*'.
        available_renderers = [
            renderer for renderer in request.renderer_classes
            if not issubclass(renderer, BrowsableAPIRenderer)
        ]
        assert available_renderers, 'BrowsableAPIRenderer cannot be the only renderer'
        mock_renderer = available_renderers[0]()
        mock_media_type = MediaType(mock_renderer.media_type)
        if data == '' and not mock_renderer.handles_empty_responses:
            mock_content = None
        else:
            text = mock_renderer.render(data, mock_media_type, indent=4)
            mock_content = self._html_escape(text)

        # Determine the allowed methods on this view.
        adapter = _request_ctx_stack.top.url_adapter
        allowed_methods = adapter.allowed_methods()

        endpoint = request.url_rule.endpoint
        view_name = str(endpoint)
        view_description = current_app.view_functions[endpoint].__doc__
        if view_description:
            if apply_markdown:
                view_description = dedent(view_description)
                view_description = apply_markdown(view_description)
            else:  # pragma: no cover - markdown installed for tests
                view_description = dedent(view_description)
                view_description = pydoc.html.preformat(view_description)

        status = options['status']
        headers = options['headers']
        headers['Content-Type'] = str(mock_media_type)

        from flask_api import __version__

        context = {
            'status': status,
            'headers': headers,
            'content': mock_content,
            'allowed_methods': allowed_methods,
            'view_name': convert_to_title(view_name),
            'view_description': view_description,
            'version': __version__
        }
        return render_template(self.template, **context)
    def select_renderer(self, renderers):
        """
        Determine which renderer to use for rendering the response body.
        Returns a two-tuple of (renderer, content type).
        """
        accept_header = request.headers.get('Accept', '*/*')

        for client_media_types in parse_accept_header(accept_header):
            for renderer in renderers:
                server_media_type = MediaType(renderer.media_type)
                for client_media_type in client_media_types:
                    if client_media_type.satisfies(server_media_type):
                        if server_media_type.precedence > client_media_type.precedence:
                            return (renderer, server_media_type)
                        else:
                            return (renderer, client_media_type)

        raise exceptions.NotAcceptable()
Exemple #17
0
 def test_media_type_sub_type_mismatch(self):
     media_type = MediaType('image/jpeg')
     other = MediaType('image/png')
     self.assertFalse(media_type.satisfies(other))
Exemple #18
0
 def test_render_json(self):
     renderer = renderers.JSONRenderer()
     content = renderer.render({'example': 'example'}, MediaType('application/json'))
     expected = '{"example": "example"}'
     self.assertEqual(content, expected)
 def test_media_type_main_type_match(self):
     media_type = MediaType('image/*')
     other = MediaType('image/png')
     assert media_type.satisfies(other)
 def test_media_type_matching_params(self):
     media_type = MediaType('application/json; version=1.0')
     other = MediaType('application/json; version=1.0')
     assert media_type.satisfies(other)
Exemple #21
0
 def test_media_type_includes_params(self):
     media_type = MediaType('application/json')
     other = MediaType('application/json; version=1.0')
     self.assertTrue(media_type.satisfies(other))
Exemple #22
0
 def test_parse_simple_accept_header(self):
     parsed = parse_accept_header('*/*, application/json')
     self.assertEqual(
         parsed,
         [set([MediaType('application/json')]),
          set([MediaType('*/*')])])
 def test_media_type_wildcard_match(self):
     media_type = MediaType('*/*')
     other = MediaType('image/png')
     self.assertTrue(media_type.satisfies(other))
 def test_media_type_wildcard_mismatch(self):
     media_type = MediaType('image/*')
     other = MediaType('audio/*')
     self.assertFalse(media_type.satisfies(other))
 def test_media_type_non_matching_params(self):
     media_type = MediaType('application/json; version=1.0')
     other = MediaType('application/json; version=2.0')
     self.assertFalse(media_type.satisfies(other))
 def test_media_type_sub_type_mismatch(self):
     media_type = MediaType('image/jpeg')
     other = MediaType('image/png')
     self.assertFalse(media_type.satisfies(other))
 def test_media_type_includes_params(self):
     media_type = MediaType('application/json')
     other = MediaType('application/json; version=1.0')
     self.assertTrue(media_type.satisfies(other))
Exemple #28
0
 def test_render_json_with_indent(self):
     renderer = renderers.JSONRenderer()
     content = renderer.render({'example': 'example'},
                               MediaType('application/json; indent=4'))
     expected = '{\n    "example": "example"\n}'
     assert content == expected
Exemple #29
0
 def test_media_type_wildcard_mismatch(self):
     media_type = MediaType('image/*')
     other = MediaType('audio/*')
     self.assertFalse(media_type.satisfies(other))
Exemple #30
0
 def test_media_type_wildcard_match(self):
     media_type = MediaType('*/*')
     other = MediaType('image/png')
     self.assertTrue(media_type.satisfies(other))
Exemple #31
0
 def test_media_type_non_matching_params(self):
     media_type = MediaType('application/json; version=1.0')
     other = MediaType('application/json; version=2.0')
     self.assertFalse(media_type.satisfies(other))