Beispiel #1
0
    def _api_name_from_headers(self, request):
        self._accept_range = request.META.get('HTTP_ACCEPT', '*/*')
        # Accepts header can look like:
        # text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        # So we need to split it apart for use with parse_media_range.
        ranges = self._accept_range.split(',')
        try:
            ranges = [mimeparse.parse_media_range(m) for m in ranges]
        except ValueError:
            raise BadRequest('Incorrect accept header')
        # Then sort the accepted types by their quality, best first.
        ranges.sort(
            lambda x, y: cmp(float(y[2].get('q')), float(x[2].get('q'))))
        for range in ranges:
            subtype = range[1]
            for api_name in self._registry.keys():
                # We enforce the vnd.api.<api_name>+<type> convention to keep
                # things simple.  E.g. vnd.api.myapi-v2+json or
                # vnd.api.djangoappv3+xml
                api_subtype = '{}+'.format(
                    self.api_subtype.format(api_name=api_name))
                if subtype.startswith(api_subtype):
                    # This is our match.
                    # Rewrite the Accepts header, removing our
                    # vendor-specific api name so that the rest of our logic
                    # works the same way.
                    request.META['HTTP_ACCEPT'] = self._accept_range.replace(
                        api_subtype, '')
                    return api_name

        return self._default_api_name
Beispiel #2
0
    def _api_name_from_headers(self, request):
        self._accept_range = request.META.get("HTTP_ACCEPT", "*/*")
        # Accepts header can look like:
        # text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        # So we need to split it apart for use with parse_media_range.
        ranges = self._accept_range.split(",")
        try:
            ranges = [mimeparse.parse_media_range(m) for m in ranges]
        except ValueError:
            raise BadRequest("Incorrect accept header")
        # Then sort the accepted types by their quality, best first.
        ranges.sort(lambda x, y: cmp(float(y[2].get("q")), float(x[2].get("q"))))
        for range in ranges:
            subtype = range[1]
            for api_name in self._registry.keys():
                # We enforce the vnd.api.<api_name>+<type> convention to keep
                # things simple.  E.g. vnd.api.myapi-v2+json or
                # vnd.api.djangoappv3+xml
                api_subtype = "{}+".format(self.api_subtype.format(api_name=api_name))
                if subtype.startswith(api_subtype):
                    # This is our match.
                    # Rewrite the Accepts header, removing our
                    # vendor-specific api name so that the rest of our logic
                    # works the same way.
                    request.META["HTTP_ACCEPT"] = self._accept_range.replace(api_subtype, "")
                    return api_name

        return self._default_api_name
def quality_and_fitness_parsed(
        mime_type: str, parsed_ranges: List[MimeTypeComponents]) -> QFParsed:
    """Find the best match for a mime-type amongst parsed media-ranges.

    Find the best match for a given mime-type against a list of media_ranges
    that have already been parsed by parse_media_range(). Returns a tuple of
    the fitness value and the value of the 'q' quality parameter of the best
    match, or (-1, 0) if no match was found. Just as for quality_parsed(),
    'parsed_ranges' must be a list of parsed media ranges.

    Cherry-picked from python-mimeparse and improved.
    """
    best_fitness = -1
    best_fit_q = 0
    (target_type, target_subtype, target_params) = parse_media_range(mime_type)
    best_matched = None

    for (type, subtype, params) in parsed_ranges:

        # check if the type and the subtype match
        type_match = (type in (target_type, '*') or target_type == '*')
        subtype_match = (subtype in (target_subtype, '*')
                         or target_subtype == '*')

        # if they do, assess the "fitness" of this mime_type
        if type_match and subtype_match:

            # 100 points if the type matches w/o a wildcard
            fitness = type == target_type and 100 or 0

            # 10 points if the subtype matches w/o a wildcard
            fitness += subtype == target_subtype and 10 or 0

            # 1 bonus point for each matching param besides "q"
            param_matches = sum([
                1 for (key, value) in target_params.items()
                if key != 'q' and key in params and value == params[key]
            ])
            fitness += param_matches

            # finally, add the target's "q" param (between 0 and 1)
            fitness += float(target_params.get('q', 1))

            if fitness > best_fitness:
                best_fitness = fitness
                best_fit_q = params['q']
                best_matched = (type, subtype, params)

    return (float(best_fit_q), best_fitness), best_matched
Beispiel #4
0
    def quality(self, accept=None, accept_charset=None,
                accept_language=None):
        """
        :param accept: string in the same format as an http `Accept` header

        :param accept_language: string in the same format as an http
            `Accept-Language` header

        :param accept_charset: string in the same format as an http
            `Accept-Charset` header

        :return: a number or tuple of tuples representing the quality of
            the match. By convention outer tuples should be in content type,
            language, charset order.  Raises `NotAcceptable If the binding does
            not match the request.

        """
        if self.content_type is None:
            # TODO
            return 5, self.qs

        if accept is None:
            return 0, self.qs

        accept = [
            mimeparse.parse_media_range(media_range)
            for media_range in accept.split(',')
        ]

        fitness, quality = mimeparse.fitness_and_quality_parsed(
            self.content_type, accept
        )

        if fitness == -1:
            raise NotAcceptable()

        return fitness, quality * self.qs
def best_match(supported: IterableType[str],
               header: str) -> Tuple[str, Optional[MimeTypeComponents]]:
    """Return mime-type with the highest quality ('q') from list of candidates.
    Takes a list of supported mime-types and finds the best match for all the
    media-ranges listed in header. The value of header must be a string that
    conforms to the format of the HTTP Accept: header. The value of 'supported'
    is a list of mime-types. The list of supported mime-types should be sorted
    in order of increasing desirability, in case of a situation where there is
    a tie.

    Cherry-picked from python-mimeparse and improved.

    >>> best_match(['application/xbel+xml', 'text/xml'],
                   'text/*;q=0.5,*/*; q=0.1')
    ('text/xml', ('text', '*', {'q': '0.5'}))
    """
    split_header = _filter_blank(header.split(','))
    parsed_header = [parse_media_range(r) for r in split_header]
    weighted_matches = {}
    for i, mime_type in enumerate(supported):
        weight, match = quality_and_fitness_parsed(mime_type, parsed_header)
        weighted_matches[(weight, i)] = (mime_type, match)
    best = max(weighted_matches.keys())
    return best[0][0] and weighted_matches[best] or ('', None)
 def _test_parse_media_range(self, args, expected):
     expected = tuple(expected)
     result = mimeparse.parse_media_range(args)
     message = "Expected: '%s' but got %s" % (expected, result)
     self.assertEqual(expected, result, message)
def test_parse_media_range(args, expected):
    expected = tuple(expected)
    result = mimeparse.parse_media_range(args)
    message = "Expected: '%s' but got %s" % (expected, result)
    assert expected == result, message
Beispiel #8
0
import logging
import re
from collections import namedtuple
from enum import Enum, Flag, auto

from mimeparse import parse_media_range

#: Logger instance
logger = logging.getLogger('aiohttp-json-api')

#: Key of JSON API stuff in aiohttp.web.Application
JSONAPI = 'jsonapi'

#: JSON API Content-Type by specification
JSONAPI_CONTENT_TYPE = 'application/vnd.api+json'
JSONAPI_CONTENT_TYPE_PARSED = parse_media_range(JSONAPI_CONTENT_TYPE)

#: Regular expression rule for check allowed fields and types names
ALLOWED_MEMBER_NAME_RULE = \
    r'[a-zA-Z0-9]([a-zA-Z0-9\-_]+[a-zA-Z0-9]|[a-zA-Z0-9]?)'

#: Compiled regexp of rule
ALLOWED_MEMBER_NAME_REGEX = re.compile('^' + ALLOWED_MEMBER_NAME_RULE + '$')

#: Filter rule
FilterRule = namedtuple('FilterRule', ('name', 'value'))

#: JSON API resource identifier
ResourceID = collections.namedtuple('ResourceID', ['type', 'id'])