webob — Request/Response objects

Headers

Accept*

Parse four Accept* headers used in server-driven content negotiation.

The four headers are Accept, Accept-Charset, Accept-Encoding and Accept-Language.

Convenience functions to automatically create the appropriate header objects of a certain type:

webob.acceptparse.create_accept_header(header_value)

Create an object representing the Accept header in a request.

Parameters:header_value — (str) header value
Returns:If header_value is None, an AcceptNoHeader instance.
If header_value is a valid Accept header, an AcceptValidHeader instance.
If header_value is an invalid Accept header, an AcceptInvalidHeader instance.

webob.acceptparse.create_accept_charset_header(header_value)

Create an object representing the Accept-Charset header in a request.

Parameters:header_value — (str) header value
Returns:If header_value is None, an AcceptCharsetNoHeader instance.
If header_value is a valid Accept-Charset header, an AcceptCharsetValidHeader instance.
If header_value is an invalid Accept-Charset header, an AcceptCharsetInvalidHeader instance.

webob.acceptparse.create_accept_encoding_header(header_value)

Create an object representing the Accept-Encoding header in a request.

Parameters:header_value — (str) header value
Returns:If header_value is None, an AcceptEncodingNoHeader instance.
If header_value is a valid Accept-Encoding header, an AcceptEncodingValidHeader instance.
If header_value is an invalid Accept-Encoding header, an AcceptEncodingInvalidHeader instance.

webob.acceptparse.create_accept_language_header(header_value)

Create an object representing the Accept-Language header in a request.

Parameters:header_value — (str) header value
Returns:If header_value is None, an AcceptLanguageNoHeader instance.
If header_value is a valid Accept-Language header, an AcceptLanguageValidHeader instance.
If header_value is an invalid Accept-Language header, an AcceptLanguageInvalidHeader instance.

The classes that may be returned by one of the functions above, and their methods:

class webob.acceptparse.Accept

Represent an Accept header.

Base class for AcceptValidHeader, AcceptNoHeader, and AcceptInvalidHeader.

  • classmethod parse(value)

    Parse an Accept header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept header, returns an iterator of (media_range, qvalue, media_type_params, extension_params) tuples, as parsed from the header from left to right.
    media_range is the media range, including any media type parameters. The media range is returned in a canonicalised form (except the case of the characters are unchanged): unnecessary spaces around the semicolons before media type parameters are removed; the parameter values are returned in a form where only the ‘\‘ and ‘‘ characters are escaped, and the values are quoted with double quotes only if they need to be quoted.
    qvalue is the quality value of the media range.
    media_type_params is the media type parameters, as a list of (parameter name, value) tuples.
    extension_params is the extension parameters, as a list where each item is either a parameter string or a (parameter name, value) tuple.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptOffer

A pre-parsed offer tuple represeting a value in the format type/subtype;param0=value0;param1=value1.

Variables:
  • type — The media type’s root category.
  • subtype — The media type’s subtype.
  • params — A tuple of 2-tuples containing parameter names and values.
  • __str__()

    Return the properly quoted media type string.

class webob.acceptparse.AcceptValidHeader(header_value)

Represent a valid Accept header.

A valid header is one that conforms to RFC 7231, section 5.3.2.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptValidHeader.__add__()).

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    A list of (media_range, qvalue, media_type_params, extension_params) tuples, where

    media_range is the media range, including any media type parameters. The media range is returned in a canonicalised form (except the case of the characters are unchanged): unnecessary spaces around the semicolons before media type parameters are removed; the parameter values are returned in a form where only the ‘\‘ and ‘"‘ characters are escaped, and the values are quoted with double quotes only if they need to be quoted.

    qvalue is the quality value of the media range.

    media_type_params is the media type parameters, as a list of (parameter name, value) tuples.

    extension_params is the extension parameters, as a list where each item is either a parameter string or a (parameter name, value) tuple.

  • __init__(header_value)

    Create an AcceptValidHeader instance.

    Parameters:header_value — (str) header value.
    Raises:ValueError — if header_value is an invalid value for an Accept header.
  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with media ranges str‘s (including any media type parameters) as keys, and either qvalues float‘s or (qvalues, extension_params) tuples as values, where extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • a tuple or list, where each item is either a header element str, or a (media_range, qvalue, extension_params) tuple or list where media_range is a str of the media range including any media type parameters, and extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • an AcceptValidHeader, AcceptNoHeader, or AcceptInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or another AcceptValidHeader instance, and the header value it represents is not ‘’, then the two header values are joined with ', ', and a new AcceptValidHeader instance with the new header value is returned.

    If other is a valid header value or another AcceptValidHeader instance representing a header value of ‘’; or if it is None or an AcceptNoHeader instance; or if it is an invalid header value, or an AcceptInvalidHeader instance, then a new AcceptValidHeader instance with the same header value as self is returned.

  • __bool__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __nonzero__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of AcceptValidHeader.__contains__() is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) media type offer
    Returns:(bool) Whether offer is acceptable according to the header.

    This uses the old criterion of a match in AcceptValidHeader._old_match(), which is not as specified in RFC 7231, section 5.3.2. It does not correctly take into account media type parameters:

    1. >>> 'text/html;p=1' in AcceptValidHeader('text/html')
    2. False

    or media ranges with q=0 in the header:

    1. >>> 'text/html' in AcceptValidHeader('text/*, text/html;q=0')
    2. True
    3. >>> 'text/html' in AcceptValidHeader('text/html;q=0, */*')
    4. True

    (See the docstring for AcceptValidHeader._old_match() for other problems with the old criterion for matching.)

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the media ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    Please note that this is a simple filter for the ranges in the header with non-0 qvalues, and is not necessarily the same as what the client prefers, e.g. 'audio/basic;q=0, */*' means ‘everything but audio/basic’, but list(instance) would return only ['*/*'].

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return a tidied up version of the header value.

    e.g. If self.header_value is r',,text/html ; p1="\"\1\"" ; q=0.50; e1=1 ;e2 , text/plain ,', str(instance) returns r'text/html;p1="\"1\"";q=0.5;e1=1;e2, text/plain'.

  • accept_html()

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

  • accepts_html

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    The offers are returned in descending order of preference, where preference is indicated by the qvalue of the media range in the header that best matches the offer.

    This uses the matching rules described in RFC 7231, section 5.3.2.

    Any offers that cannot be parsed via Accept.parse_offer() will be ignored.

    Parameters:offersiterable of str media types (media types can include media type parameters) or pre-parsed instances of AcceptOffer.
    Returns:A list of tuples of the form (media type, qvalue), in descending order of qvalue. Where two offers have the same qvalue, they are returned in the same order as their order in offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of media type offers.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    AcceptValidHeader.best_match() uses its own algorithm (one not specified in RFC 7231) to determine what is a best match. The algorithm has many issues, and does not conform to RFC 7231.

    Each media type in offers is checked against each non-q=0 range in the header. If the two are a match according to WebOb’s old criterion for a match, the quality value of the match is the qvalue of the media range from the header multiplied by the server quality value of the offer (if the server quality value is not supplied, it is 1).

    The offer in the match with the highest quality value is the best match. If there is more than one match with the highest qvalue, the match where the media range has a lower number of ‘*‘s is the best match. If the two have the same number of ‘*‘s, the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str media type, or a (media type, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if there is no match
    Returns:

    (str, or the type of default_match)

    The offer that is the best match. If there is no match, the value of default_match is returned.

    This uses the old criterion of a match in AcceptValidHeader._old_match(), which is not as specified in RFC 7231, section 5.3.2. It does not correctly take into account media type parameters:

    1. >>> instance = AcceptValidHeader('text/html')
    2. >>> instance.best_match(offers=['text/html;p=1']) is None
    3. True

    or media ranges with q=0 in the header:

    1. >>> instance = AcceptValidHeader('text/*, text/html;q=0')
    2. >>> instance.best_match(offers=['text/html'])
    3. 'text/html'
    4. >>> instance = AcceptValidHeader('text/html;q=0, */*')
    5. >>> instance.best_match(offers=['text/html'])
    6. 'text/html'

    (See the docstring for AcceptValidHeader._old_match() for other problems with the old criterion for matching.)

    Another issue is that this method considers the best matching range for an offer to be the matching range with the highest quality value, (where quality values are tied, the most specific media range is chosen); whereas RFC 7231, section 5.3.2 specifies that we should consider the best matching range for a media type offer to be the most specific matching range.:

    1. >>> instance = AcceptValidHeader('text/html;q=0.5, text/*')
    2. >>> instance.best_match(offers=['text/html', 'text/plain'])
    3. 'text/html'
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    Parameters:offer — (str) media type offer
    Returns:(float or None)
    The highest quality value from the media range(s) that match the offer, or None if there is no match.

    This uses the old criterion of a match in AcceptValidHeader._old_match(), which is not as specified in RFC 7231, section 5.3.2. It does not correctly take into account media type parameters:

    1. >>> instance = AcceptValidHeader('text/html')
    2. >>> instance.quality('text/html;p=1') is None
    3. True

    or media ranges with q=0 in the header:

    1. >>> instance = AcceptValidHeader('text/*, text/html;q=0')
    2. >>> instance.quality('text/html')
    3. 1.0
    4. >>> AcceptValidHeader('text/html;q=0, */*').quality('text/html')
    5. 1.0

    (See the docstring for AcceptValidHeader._old_match() for other problems with the old criterion for matching.)

    Another issue is that this method considers the best matching range for an offer to be the matching range with the highest quality value, whereas RFC 7231, section 5.3.2 specifies that we should consider the best matching range for a media type offer to be the most specific matching range.:

    1. >>> instance = AcceptValidHeader('text/html;q=0.5, text/*')
    2. >>> instance.quality('text/html')
    3. 1.0
  • classmethod parse(value)

    Parse an Accept header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept header, returns an iterator of (media_range, qvalue, media_type_params, extension_params) tuples, as parsed from the header from left to right.
    media_range is the media range, including any media type parameters. The media range is returned in a canonicalised form (except the case of the characters are unchanged): unnecessary spaces around the semicolons before media type parameters are removed; the parameter values are returned in a form where only the ‘\‘ and ‘‘ characters are escaped, and the values are quoted with double quotes only if they need to be quoted.
    qvalue is the quality value of the media range.
    media_type_params is the media type parameters, as a list of (parameter name, value) tuples.
    extension_params is the extension parameters, as a list where each item is either a parameter string or a (parameter name, value) tuple.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptNoHeader

Represent when there is no Accept header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptNoHeader.__add__()).

  • header_value

    (str or None) The header value.

    As there is no header in the request, this is None.

  • parsed

    (list or None) Parsed form of the header.

    As there is no header in the request, this is None.

  • __init__()

    Create an AcceptNoHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with media ranges str‘s (including any media type parameters) as keys, and either qvalues float‘s or (qvalues, extension_params) tuples as values, where extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • a tuple or list, where each item is either a header element str, or a (media_range, qvalue, extension_params) tuple or list where media_range is a str of the media range including any media type parameters, and extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • an AcceptValidHeader, AcceptNoHeader, or AcceptInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptValidHeader instance, a new AcceptValidHeader instance with the valid header value is returned.

    If other is None, an AcceptNoHeader instance, an invalid header value, or an AcceptInvalidHeader instance, a new AcceptNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptNoHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<no header in request>'.

  • __bool__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the Accept classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) media type offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept header in the request, or the header is invalid, so any media type is acceptable, and this always returns True.

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the media ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept header in the request or the header is invalid, there are no media ranges, so this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • accept_html()

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this always returns True.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    Any offers that cannot be parsed via Accept.parse_offer() will be ignored.

    Parameters:offersiterable of str media types (media types can include media type parameters)
    Returns:When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this method returns a list of (media type, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as in offers.
  • accepts_html

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this always returns True.

  • best_match(offers, default_match=None)

    Return the best match from the sequence of language tag offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptValidHeader.best_match()).

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so the best match is the media type in offers with the highest server quality value (if the server quality value is not supplied for a media type, it is 1).

    If more than one media type in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str media type, or a (media type, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The offer that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept header, returns an iterator of (media_range, qvalue, media_type_params, extension_params) tuples, as parsed from the header from left to right.
    media_range is the media range, including any media type parameters. The media range is returned in a canonicalised form (except the case of the characters are unchanged): unnecessary spaces around the semicolons before media type parameters are removed; the parameter values are returned in a form where only the ‘\‘ and ‘‘ characters are escaped, and the values are quoted with double quotes only if they need to be quoted.
    qvalue is the quality value of the media range.
    media_type_params is the media type parameters, as a list of (parameter name, value) tuples.
    extension_params is the extension parameters, as a list where each item is either a parameter string or a (parameter name, value) tuple.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptValidHeader.quality()).

    Parameters:offer — (str) media type offer
    Returns:(float) 1.0.

    When the Accept header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptInvalidHeader(header_value)

Represent an invalid Accept header.

An invalid header is one that does not conform to RFC 7231#section-5.3.2.

RFC 7231 does not provide any guidance on what should happen if the Accept header has an invalid value. This implementation disregards the header, and treats it as if there is no Accept header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptInvalidHeader.__add__()).

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    As the header is invalid and cannot be parsed, this is None.

  • __init__(header_value)

    Create an AcceptInvalidHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with media ranges str‘s (including any media type parameters) as keys, and either qvalues float‘s or (qvalues, extension_params) tuples as values, where extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • a tuple or list, where each item is either a header element str, or a (media_range, qvalue, extension_params) tuple or list where media_range is a str of the media range including any media type parameters, and extension_params is a str of the extension parameters segment of the header element, starting with the first ‘;
    • an AcceptValidHeader, AcceptNoHeader, or AcceptInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptValidHeader instance, then a new AcceptValidHeader instance with the valid header value is returned.

    If other is None, an AcceptNoHeader instance, an invalid header value, or an AcceptInvalidHeader instance, a new AcceptNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<invalid header value>'.

  • __bool__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the Accept classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) media type offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept header in the request, or the header is invalid, so any media type is acceptable, and this always returns True.

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the media ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept header in the request or the header is invalid, there are no media ranges, so this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • accept_html()

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this always returns True.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    Any offers that cannot be parsed via Accept.parse_offer() will be ignored.

    Parameters:offersiterable of str media types (media types can include media type parameters)
    Returns:When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this method returns a list of (media type, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as in offers.
  • accepts_html

    Return True if any HTML-like type is accepted.

    The HTML-like types are ‘text/html’, ‘application/xhtml+xml’, ‘application/xml’ and ‘text/xml’.

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so this always returns True.

  • best_match(offers, default_match=None)

    Return the best match from the sequence of language tag offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptValidHeader.best_match()).

    When the header is invalid, or there is no Accept header in the request, all offers are considered acceptable, so the best match is the media type in offers with the highest server quality value (if the server quality value is not supplied for a media type, it is 1).

    If more than one media type in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str media type, or a (media type, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The offer that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept header, returns an iterator of (media_range, qvalue, media_type_params, extension_params) tuples, as parsed from the header from left to right.
    media_range is the media range, including any media type parameters. The media range is returned in a canonicalised form (except the case of the characters are unchanged): unnecessary spaces around the semicolons before media type parameters are removed; the parameter values are returned in a form where only the ‘\‘ and ‘‘ characters are escaped, and the values are quoted with double quotes only if they need to be quoted.
    qvalue is the quality value of the media range.
    media_type_params is the media type parameters, as a list of (parameter name, value) tuples.
    extension_params is the extension parameters, as a list where each item is either a parameter string or a (parameter name, value) tuple.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptValidHeader.quality()).

    Parameters:offer — (str) media type offer
    Returns:(float) 1.0.

    When the Accept header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptCharset

Represent an Accept-Charset header.

Base class for AcceptCharsetValidHeader, AcceptCharsetNoHeader, and AcceptCharsetInvalidHeader.

  • classmethod parse(value)

    Parse an Accept-Charset header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Charset header, returns an iterator of (charset, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptCharsetValidHeader(header_value)

Represent a valid Accept-Charset header.

A valid header is one that conforms to RFC 7231, section 5.3.3.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptCharsetValidHeader.__add__()).

  • header_value

    (str) The header value.

  • parsed

    (list) Parsed form of the header.

    A list of (charset, quality value) tuples.

  • __init__(header_value)

    Create an AcceptCharsetValidHeader instance.

    Parameters:header_value — (str) header value.
    Raises:ValueError — if header_value is an invalid value for an Accept-Charset header.
  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, where keys are charsets and values are qvalues
    • a tuple or list, where each item is a charset str or a tuple or list (charset, qvalue) pair (str‘s and pairs can be mixed within the tuple or list)
    • an AcceptCharsetValidHeader, AcceptCharsetNoHeader, or AcceptCharsetInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or another AcceptCharsetValidHeader instance, the two header values are joined with ', ', and a new AcceptCharsetValidHeader instance with the new header value is returned.

    If other is None, an AcceptCharsetNoHeader instance, an invalid header value, or an AcceptCharsetInvalidHeader instance, a new AcceptCharsetValidHeader instance with the same header value as self is returned.

  • __bool__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __nonzero__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of AcceptCharsetValidHeader.__contains__() is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) charset offer
    Returns:(bool) Whether offer is acceptable according to the header.

    This does not fully conform to RFC 7231, section 5.3.3: it incorrect interprets * to mean ‘match any charset in the header’, rather than ‘match any charset that is not mentioned elsewhere in the header’:

    1. >>> 'UTF-8' in AcceptCharsetValidHeader('UTF-8;q=0, *')
    2. True
  • __iter__()

    Return all the items with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the items (charset or *) in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    Please note that this is a simple filter for the items in the header with non-0 qvalues, and is not necessarily the same as what the client prefers, e.g. 'utf-7;q=0, *' means ‘everything but utf-7’, but list(instance) would return only ['*'].

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptCharsetValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return a tidied up version of the header value.

    e.g. If the header_value is ', \t,iso-8859-5;q=0.000 \t, utf-8;q=1.000, UTF-7, unicode-1-1;q=0.210 ,', str(instance) returns 'iso-8859-5;q=0, utf-8, UTF-7, unicode-1-1;q=0.21'.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    The offers are returned in descending order of preference, where preference is indicated by the qvalue of the charset or * in the header matching the offer.

    This uses the matching rules described in RFC 7231, section 5.3.3.

    Parameters:offersiterable of str charsets
    Returns:A list of tuples of the form (charset, qvalue), in descending order of qvalue. Where two offers have the same qvalue, they are returned in the same order as their order in offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of charset offers.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    AcceptCharsetValidHeader.best_match() has many issues, and does not conform to RFC 7231.

    Each charset in offers is checked against each non-q=0 item (charset or *) in the header. If the two are a match according to WebOb’s old criterion for a match, the quality value of the match is the qvalue of the item from the header multiplied by the server quality value of the offer (if the server quality value is not supplied, it is 1).

    The offer in the match with the highest quality value is the best match. If there is more than one match with the highest qvalue, the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str charset, or a (charset, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if there is no match
    Returns:

    (str, or the type of default_match)

    The offer that is the best match. If there is no match, the value of default_match is returned.

    The algorithm behind this method was written for the Accept header rather than the Accept-Charset header. It uses the old criterion of a match in AcceptCharsetValidHeader._old_match(), which does not conform to RFC 7231, section 5.3.3, in that it does not interpret * values in the header correctly: * should only match charsets not mentioned elsewhere in the header:

    1. >>> AcceptCharsetValidHeader('utf-8;q=0, *').best_match(['utf-8'])
    2. 'utf-8'
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    Parameters:offer — (str) charset offer
    Returns:(float or None)
    The quality value from the charset that matches the offer, or None if there is no match.

    This uses the old criterion of a match in AcceptCharsetValidHeader._old_match(), which does not conform to RFC 7231, section 5.3.3, in that it does not interpret * values in the header correctly: * should only match charsets not mentioned elsewhere in the header:

    1. >>> AcceptCharsetValidHeader('utf-8;q=0, *').quality('utf-8')
    2. 1.0
    3. >>> AcceptCharsetValidHeader('utf-8;q=0.9, *').quality('utf-8')
    4. 1.0
  • classmethod parse(value)

    Parse an Accept-Charset header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Charset header, returns an iterator of (charset, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptCharsetNoHeader

Represent when there is no Accept-Charset header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptCharsetNoHeader.__add__()).

  • header_value

    (str or None) The header value.

    As there is no header in the request, this is None.

  • parsed

    (list or None) Parsed form of the header.

    As there is no header in the request, this is None.

  • __init__()

    Create an AcceptCharsetNoHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, where keys are charsets and values are qvalues
    • a tuple or list, where each item is a charset str or a tuple or list (charset, qvalue) pair (str‘s and pairs can be mixed within the tuple or list)
    • an AcceptCharsetValidHeader, AcceptCharsetNoHeader, or AcceptCharsetInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptCharsetValidHeader instance, a new AcceptCharsetValidHeader instance with the valid header value is returned.

    If other is None, an AcceptCharsetNoHeader instance, an invalid header value, or an AcceptCharsetInvalidHeader instance, a new AcceptCharsetNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptCharsetNoHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<no header in request>'.

  • __bool__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the AcceptCharset classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) charset offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Charset header in the request, or the header is invalid, so any charset is acceptable, and this always returns True.

  • __iter__()

    Return all the items with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the items (charset or *) in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept-Charset header in the request or the header is invalid, there are no items, and this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    The offers are returned in descending order of preference, where preference is indicated by the qvalue of the charset or * in the header matching the offer.

    This uses the matching rules described in RFC 7231, section 5.3.3.

    Parameters:offersiterable of str charsets
    Returns:A list of tuples of the form (charset, qvalue), in descending order of qvalue. Where two offers have the same qvalue, they are returned in the same order as their order in offers.
    When the header is invalid or there is no Accept-Charset header in the request, all offers are considered acceptable, so this method returns a list of (charset, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of charset offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptCharsetValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptCharsetValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Charset header in the request, all the charsets in offers are considered acceptable, so the best match is the charset in offers with the highest server quality value (if the server quality value is not supplied, it is 1).

    If more than one charsets in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str charset, or a (charset, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The charset that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept-Charset header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Charset header, returns an iterator of (charset, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptCharsetValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptCharsetValidHeader.quality()).

    Parameters:offer — (str) charset offer
    Returns:(float) 1.0.

    When the Accept-Charset header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptCharsetInvalidHeader(header_value)

Represent an invalid Accept-Charset header.

An invalid header is one that does not conform to RFC 7231#section-5.3.3. As specified in the RFC, an empty header is an invalid Accept-Charset header.

RFC 7231 does not provide any guidance on what should happen if the Accept-Charset header has an invalid value. This implementation disregards the header, and treats it as if there is no Accept-Charset header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptCharsetInvalidHeader.__add__()).

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    As the header is invalid and cannot be parsed, this is None.

  • __init__(header_value)

    Create an AcceptCharsetInvalidHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, where keys are charsets and values are qvalues
    • a tuple or list, where each item is a charset str or a tuple or list (charset, qvalue) pair (str‘s and pairs can be mixed within the tuple or list)
    • an AcceptCharsetValidHeader, AcceptCharsetNoHeader, or AcceptCharsetInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptCharsetValidHeader instance, a new AcceptCharsetValidHeader instance with the valid header value is returned.

    If other is None, an AcceptCharsetNoHeader instance, an invalid header value, or an AcceptCharsetInvalidHeader instance, a new AcceptCharsetNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptCharsetValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<invalid header value>'.

  • __bool__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the AcceptCharset classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) charset offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Charset header in the request, or the header is invalid, so any charset is acceptable, and this always returns True.

  • __iter__()

    Return all the items with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the items (charset or *) in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept-Charset header in the request or the header is invalid, there are no items, and this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept-Charset header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    The offers are returned in descending order of preference, where preference is indicated by the qvalue of the charset or * in the header matching the offer.

    This uses the matching rules described in RFC 7231, section 5.3.3.

    Parameters:offersiterable of str charsets
    Returns:A list of tuples of the form (charset, qvalue), in descending order of qvalue. Where two offers have the same qvalue, they are returned in the same order as their order in offers.
    When the header is invalid or there is no Accept-Charset header in the request, all offers are considered acceptable, so this method returns a list of (charset, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of charset offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptCharsetValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptCharsetValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Charset header in the request, all the charsets in offers are considered acceptable, so the best match is the charset in offers with the highest server quality value (if the server quality value is not supplied, it is 1).

    If more than one charsets in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str charset, or a (charset, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The charset that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept-Charset header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Charset header, returns an iterator of (charset, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptCharsetValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptCharsetValidHeader.quality()).

    Parameters:offer — (str) charset offer
    Returns:(float) 1.0.

    When the Accept-Charset header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptEncoding

Represent an Accept-Encoding header.

Base class for AcceptEncodingValidHeader, AcceptEncodingNoHeader, and AcceptEncodingInvalidHeader.

  • classmethod parse(value)

    Parse an Accept-Encoding header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Encoding header, returns an iterator of (codings, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptEncodingValidHeader(header_value)

Represent a valid Accept-Encoding header.

A valid header is one that conforms to RFC 7231, section 5.3.4.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptEncodingValidHeader.__add__()).

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    A list of (codings, qvalue) tuples, where

    codings (str) is a content-coding, the string “identity“, or “*“; and

    qvalue (float) is the quality value of the codings.

  • __init__(header_value)

    Create an AcceptEncodingValidHeader instance.

    Parameters:header_value — (str) header value.
    Raises:ValueError — if header_value is an invalid value for an Accept-Encoding header.
  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with content-coding, identity or * str‘s as keys, and qvalue float‘s as values
    • a tuple or list, where each item is either a header element str, or a (content-coding/identity/*, qvalue) tuple or list
    • an AcceptEncodingValidHeader, AcceptEncodingNoHeader, or AcceptEncodingInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or another AcceptEncodingValidHeader instance, and the header value it represents is not '', then the two header values are joined with ', ', and a new AcceptEncodingValidHeader instance with the new header value is returned.

    If other is a valid header value or another AcceptEncodingValidHeader instance representing a header value of ''; or if it is None or an AcceptEncodingNoHeader instance; or if it is an invalid header value, or an AcceptEncodingInvalidHeader instance, then a new AcceptEncodingValidHeader instance with the same header value as self is returned.

  • __bool__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __nonzero__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns True.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of AcceptEncodingValidHeader.__contains__() is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) a content-coding or identity offer
    Returns:(bool) Whether offer is acceptable according to the header.

    The behavior of this method does not fully conform to RFC 7231. It does not correctly interpret *:

    1. >>> 'gzip' in AcceptEncodingValidHeader('gzip;q=0, *')
    2. True

    and does not handle the identity token correctly:

    1. >>> 'identity' in AcceptEncodingValidHeader('gzip')
    2. False
  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the (content-coding/identity/*) items in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    Please note that this is a simple filter for the items in the header with non-0 qvalues, and is not necessarily the same as what the client prefers, e.g. 'gzip;q=0, *' means ‘everything but gzip’, but list(instance) would return only ['*'].

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptEncodingValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return a tidied up version of the header value.

    e.g. If the header_value is ",\t, a ;\t q=0.20 , b ,',", str(instance) returns "a;q=0.2, b, '".

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    The offers are returned in descending order of preference, where preference is indicated by the qvalue of the item (content-coding, “identity” or “*“) in the header that matches the offer.

    This uses the matching rules described in RFC 7231, section 5.3.4.

    Parameters:offersiterable of strs, where eachstr is a content-coding or the string identity (the token used to represent “no encoding”)
    Returns:A list of tuples of the form (content-coding or “identity”, qvalue), in descending order of qvalue. Where two offers have the same qvalue, they are returned in the same order as their order in offers.

    Use the string 'identity' (without the quotes) in offers to indicate an offer with no content-coding. From the RFC: ‘If the representation has no content-coding, then it is acceptable by default unless specifically excluded by the Accept-Encoding field stating either “identity;q=0” or “*;q=0” without a more specific entry for “identity”.’ The RFC does not specify the qvalue that should be assigned to the representation/offer with no content-coding; this implementation assigns it a qvalue of 1.0.

  • best_match(offers, default_match=None)

    Return the best match from the sequence of offers.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    AcceptEncodingValidHeader.best_match() uses its own algorithm (one not specified in RFC 7231) to determine what is a best match. The algorithm has many issues, and does not conform to the RFC.

    Each offer in offers is checked against each non-q=0 item (content-coding/identity/*) in the header. If the two are a match according to WebOb’s old criterion for a match, the quality value of the match is the qvalue of the item from the header multiplied by the server quality value of the offer (if the server quality value is not supplied, it is 1).

    The offer in the match with the highest quality value is the best match. If there is more than one match with the highest qvalue, the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str codings, or a (codings, server quality value) tuple or list, where codings is either a content-coding, or the string identity (which represents no encoding). str and tuple/list elements may be mixed within the iterable.
    • default_match — (optional, any type) the value to be returned if there is no match
    Returns:

    (str, or the type of default_match)

    The offer that is the best match. If there is no match, the value of default_match is returned.

    This method does not conform to RFC 7231, section 5.3.4, in that it does not correctly interpret *:

    1. >>> AcceptEncodingValidHeader('gzip;q=0, *').best_match(['gzip'])
    2. 'gzip'

    and does not handle the identity token correctly:

    1. >>> instance = AcceptEncodingValidHeader('gzip')
    2. >>> instance.best_match(['identity']) is None
    3. True
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    Parameters:offer — (str) A content-coding, or identity.
    Returns:(float or None)
    The quality value from the header item (content-coding/identity/*) that matches the offer, or None if there is no match.

    The behavior of this method does not conform to RFC 7231, section 5.3.4, in that it does not correctly interpret *:

    1. >>> AcceptEncodingValidHeader('gzip;q=0, *').quality('gzip')
    2. 1.0

    and does not handle the identity token correctly:

    1. >>> AcceptEncodingValidHeader('gzip').quality('identity') is None
    2. True
  • classmethod parse(value)

    Parse an Accept-Encoding header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Encoding header, returns an iterator of (codings, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptEncodingNoHeader

Represent when there is no Accept-Encoding header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptEncodingNoHeader.__add__()).

  • header_value

    (str or None) The header value.

    As there is no header in the request, this is None.

  • parsed

    (list or None) Parsed form of the header.

    As there is no header in the request, this is None.

  • __init__()

    Create an AcceptEncodingNoHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with content-coding, identity or * str‘s as keys, and qvalue float‘s as values
    • a tuple or list, where each item is either a header element str, or a (content-coding/identity/*, qvalue) tuple or list
    • an AcceptEncodingValidHeader, AcceptEncodingNoHeader, or AcceptEncodingInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptEncodingValidHeader instance, a new AcceptEncodingValidHeader instance with the valid header value is returned.

    If other is None, an AcceptEncodingNoHeader instance, an invalid header value, or an AcceptEncodingInvalidHeader instance, a new AcceptEncodingNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptEncodingNoHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<no header in request>'.

  • __bool__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the Accept-Encoding classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) a content-coding or identity offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Encoding header in the request, or the header is invalid, so any content-coding is acceptable, and this always returns True.

  • __iter__()

    Return all the header items with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the (content-coding/identity/*) items in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept-Encoding header in the request or the header is invalid, there are no items in the header, so this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    Parameters:offersiterable of strs, where eachstr is a content-coding or the string identity (the token used to represent “no encoding”)
    Returns:When the header is invalid, or there is no Accept-Encoding header in the request, all offers are considered acceptable, so this method returns a list of (content-coding or “identity”, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as in offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptEncodingValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptEncodingValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Encoding header in the request, all offers are considered acceptable, so the best match is the offer in offers with the highest server quality value (if the server quality value is not supplied for a media type, it is 1).

    If more than one offer in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str codings, or a (codings, server quality value) tuple or list, where codings is either a content-coding, or the string identity (which represents no encoding). str and tuple/list elements may be mixed within the iterable.
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The offer that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept-Encoding header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Encoding header, returns an iterator of (codings, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptEncodingValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptEncodingValidHeader.quality()).

    Parameters:offer — (str) A content-coding, or identity.
    Returns:(float) 1.0.

    When the Accept-Encoding header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptEncodingInvalidHeader(header_value)

Represent an invalid Accept-Encoding header.

An invalid header is one that does not conform to RFC 7231#section-5.3.4.

RFC 7231 does not provide any guidance on what should happen if the Accept-Encoding header has an invalid value. This implementation disregards the header, and treats it as if there is no Accept-Encoding header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptEncodingInvalidHeader.__add__()).

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    As the header is invalid and cannot be parsed, this is None.

  • __init__(header_value)

    Create an AcceptEncodingInvalidHeader instance.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    • None
    • a str header value
    • a dict, with content-coding, identity or * str‘s as keys, and qvalue float‘s as values
    • a tuple or list, where each item is either a header element str, or a (content-coding/identity/*, qvalue) tuple or list
    • an AcceptEncodingValidHeader, AcceptEncodingNoHeader, or AcceptEncodingInvalidHeader instance
    • object of any other type that returns a value for __str__

    If other is a valid header value or an AcceptEncodingValidHeader instance, then a new AcceptEncodingValidHeader instance with the valid header value is returned.

    If other is None, an AcceptEncodingNoHeader instance, an invalid header value, or an AcceptEncodingInvalidHeader instance, a new AcceptEncodingNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptEncodingValidHeader.__add__().

  • __repr__()

    Return repr(self).

  • __str__()

    Return the str '<invalid header value>'.

  • __bool__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the Accept-Encoding classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) a content-coding or identity offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Encoding header in the request, or the header is invalid, so any content-coding is acceptable, and this always returns True.

  • __iter__()

    Return all the header items with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the (content-coding/identity/*) items in the header with non-0 qvalues, in descending order of qvalue. If two items have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    When there is no Accept-Encoding header in the request or the header is invalid, there are no items in the header, so this always returns an empty iterator.

  • __nonzero__()

    Return whether self represents a valid Accept-Encoding header.

    Return True if self represents a valid header, and False if it represents an invalid header, or the header not being in the request.

    For this class, it always returns False.

  • acceptable_offers(offers)

    Return the offers that are acceptable according to the header.

    Parameters:offersiterable of strs, where eachstr is a content-coding or the string identity (the token used to represent “no encoding”)
    Returns:When the header is invalid, or there is no Accept-Encoding header in the request, all offers are considered acceptable, so this method returns a list of (content-coding or “identity”, qvalue) tuples where each offer in offers is paired with the qvalue of 1.0, in the same order as in offers.
  • best_match(offers, default_match=None)

    Return the best match from the sequence of offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptEncodingValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptEncodingValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Encoding header in the request, all offers are considered acceptable, so the best match is the offer in offers with the highest server quality value (if the server quality value is not supplied for a media type, it is 1).

    If more than one offer in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str codings, or a (codings, server quality value) tuple or list, where codings is either a content-coding, or the string identity (which represents no encoding). str and tuple/list elements may be mixed within the iterable.
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The offer that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • classmethod parse(value)

    Parse an Accept-Encoding header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Encoding header, returns an iterator of (codings, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptEncodingValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptEncodingValidHeader.quality()).

    Parameters:offer — (str) A content-coding, or identity.
    Returns:(float) 1.0.

    When the Accept-Encoding header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptLanguage

Represent an Accept-Language header.

Base class for AcceptLanguageValidHeader, AcceptLanguageNoHeader, and AcceptLanguageInvalidHeader.

  • classmethod parse(value)

    Parse an Accept-Language header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Language header, returns an iterator of (language range, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptLanguageValidHeader(header_value)

Represent a valid Accept-Language header.

A valid header is one that conforms to RFC 7231, section 5.3.5.

We take the reference from the language-range syntax rule in RFC 7231, section 5.3.5 to RFC 4647, section 2.1 to mean that only basic language ranges (and not extended language ranges) are expected in the Accept-Language header.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptLanguageValidHeader.__add__()).

  • __init__(header_value)

    Create an AcceptLanguageValidHeader instance.

    Parameters:header_value — (str) header value.
    Raises:ValueError — if header_value is an invalid value for an Accept-Language header.
  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    A list of (language range, quality value) tuples.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    If other is a valid header value or another AcceptLanguageValidHeader instance, the two header values are joined with ', ', and a new AcceptLanguageValidHeader instance with the new header value is returned.

    If other is None, an AcceptLanguageNoHeader instance, an invalid header value, or an AcceptLanguageInvalidHeader instance, a new AcceptLanguageValidHeader instance with the same header value as self is returned.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of AcceptLanguageValidHeader.__contains__() is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    What is ‘acceptable’ depends on the needs of your application. RFC 7231, section 5.3.5 suggests three matching schemes from RFC 4647, two of which WebOb supports with AcceptLanguageValidHeader.basic_filtering() and AcceptLanguageValidHeader.lookup() (we interpret the RFC to mean that Extended Filtering cannot apply for the Accept-Language header, as the header only accepts basic language ranges.) If these are not suitable for the needs of your application, you may need to write your own matching using AcceptLanguageValidHeader.parsed.

    Parameters:offer — (str) language tag offer
    Returns:(bool) Whether offer is acceptable according to the header.

    This uses the old criterion of a match in AcceptLanguageValidHeader._old_match(), which does not conform to RFC 7231, section 5.3.5 or any of the matching schemes suggested there. It also does not properly take into account ranges with q=0 in the header:

    1. >>> 'en-gb' in AcceptLanguageValidHeader('en, en-gb;q=0')
    2. True
    3. >>> 'en' in AcceptLanguageValidHeader('en;q=0, *')
    4. True

    (See the docstring for AcceptLanguageValidHeader._old_match() for other problems with the old criterion for a match.)

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the language ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    Please note that this is a simple filter for the ranges in the header with non-0 qvalues, and is not necessarily the same as what the client prefers, e.g. 'en-gb;q=0, *' means ‘everything but British English’, but list(instance) would return only ['*'].

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptLanguageValidHeader.__add__().

  • __str__()

    Return a tidied up version of the header value.

    e.g. If the header_value is ', \t,de;q=0.000 \t, es;q=1.000, zh, jp;q=0.210 ,', str(instance) returns 'de;q=0, es, zh, jp;q=0.21'.

  • basic_filtering(language_tags)

    Return the tags that match the header, using Basic Filtering.

    This is an implementation of the Basic Filtering matching scheme, suggested as a matching scheme for the Accept-Language header in RFC 7231, section 5.3.5, and defined in RFC 4647, section 3.3.1. It filters the tags in the language_tags argument and returns the ones that match the header according to the matching scheme.

    Parameters:language_tags — (iterable) language tags
    Returns:A list of tuples of the form (language tag, qvalue), in descending order of qvalue. If two or more tags have the same qvalue, they are returned in the same order as that in the header of the ranges they matched. If the matched range is the same for two or more tags (i.e. their matched ranges have the same qvalue and the same position in the header), then they are returned in the same order as that in the language_tags argument. If language_tags is unordered, e.g. if it is a set or a dict, then that order may not be reliable.

    For each tag in language_tags:

    1. If the tag matches a non-* language range in the header with q=0 (meaning “not acceptable”, see RFC 7231, section 5.3.1), the tag is filtered out.
    2. The non-* language ranges in the header that do not have q=0 are considered in descending order of qvalue; where two or more language ranges have the same qvalue, they are considered in the order in which they appear in the header.
    3. A language range ‘matches a particular language tag if, in a case-insensitive comparison, it exactly equals the tag, or if it exactly equals a prefix of the tag such that the first character following the prefix is “-“.’ (RFC 4647, section 3.3.1)
    4. If the tag does not match any of the non-* language ranges, and there is a * language range in the header, then if the * language range has q=0, the language tag is filtered out, otherwise the tag is considered a match.

    (If a range (* or non-*) appears in the header more than once — this would not make sense, but is nonetheless a valid header according to the RFC — the first in the header is used for matching, and the others are ignored.)

  • best_match(offers, default_match=None)

    Return the best match from the sequence of language tag offers.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    AcceptLanguageValidHeader.best_match() uses its own algorithm (one not specified in RFC 7231) to determine what is a best match. The algorithm has many issues, and does not conform to RFC 7231.

    AcceptLanguageValidHeader.lookup() is a possible alternative for finding a best match — it conforms to, and is suggested as a matching scheme for the Accept-Language header in, RFC 7231, section 5.3.5 — but please be aware that there are differences in how it determines what is a best match. If that is not suitable for the needs of your application, you may need to write your own matching using AcceptLanguageValidHeader.parsed.

    Each language tag in offers is checked against each non-0 range in the header. If the two are a match according to WebOb’s old criterion for a match, the quality value of the match is the qvalue of the language range from the header multiplied by the server quality value of the offer (if the server quality value is not supplied, it is 1).

    The offer in the match with the highest quality value is the best match. If there is more than one match with the highest qvalue, the match where the language range has a lower number of ‘*‘s is the best match. If the two have the same number of ‘*‘s, the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str language tag, or a (language tag, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if there is no match
    Returns:

    (str, or the type of default_match)

    The language tag that is the best match. If there is no match, the value of default_match is returned.

    Issues:

    • Incorrect tiebreaking when quality values of two matches are the same (https://github.com/Pylons/webob/issues/256):

      1. >>> header = AcceptLanguageValidHeader(
      2. ... header_value='en-gb;q=1, en;q=0.8'
      3. ... )
      4. >>> header.best_match(offers=['en', 'en-GB'])
      5. 'en'
      6. >>> header.best_match(offers=['en-GB', 'en'])
      7. 'en-GB'
      8. >>> header = AcceptLanguageValidHeader(header_value='en-gb, en')
      9. >>> header.best_match(offers=['en', 'en-gb'])
      10. 'en'
      11. >>> header.best_match(offers=['en-gb', 'en'])
      12. 'en-gb'
    • Incorrect handling of q=0:

      1. >>> header = AcceptLanguageValidHeader(header_value='en;q=0, *')
      2. >>> header.best_match(offers=['en'])
      3. 'en'
      4. >>> header = AcceptLanguageValidHeader(header_value='fr, en;q=0')
      5. >>> header.best_match(offers=['en-gb'], default_match='en')
      6. 'en'
    • Matching only takes into account the first subtag when matching a range with more specific or less specific tags:

      1. >>> header = AcceptLanguageValidHeader(header_value='zh')
      2. >>> header.best_match(offers=['zh-Hans-CN'])
      3. 'zh-Hans-CN'
      4. >>> header = AcceptLanguageValidHeader(header_value='zh-Hans')
      5. >>> header.best_match(offers=['zh-Hans-CN'])
      6. >>> header.best_match(offers=['zh-Hans-CN']) is None
      7. True
      8. >>> header = AcceptLanguageValidHeader(header_value='zh-Hans-CN')
      9. >>> header.best_match(offers=['zh'])
      10. 'zh'
      11. >>> header.best_match(offers=['zh-Hans'])
      12. >>> header.best_match(offers=['zh-Hans']) is None
      13. True
  • lookup(language_tags, default_range=None, default_tag=None, default=None)

    Return the language tag that best matches the header, using Lookup.

    This is an implementation of the Lookup matching scheme, suggested as a matching scheme for the Accept-Language header in RFC 7231, section 5.3.5, and described in RFC 4647, section 3.4.

    Each language range in the header is considered in turn, by descending order of qvalue; where qvalues are tied, ranges are considered from left to right.

    Each language range in the header represents the most specific tag that is an acceptable match: Lookup progressively truncates subtags from the end of the range until a matching language tag is found. An example is given in RFC 4647, section 3.4, under “Example of a Lookup Fallback Pattern”:

    1. Range to match: zh-Hant-CN-x-private1-private2
    2. 1. zh-Hant-CN-x-private1-private2
    3. 2. zh-Hant-CN-x-private1
    4. 3. zh-Hant-CN
    5. 4. zh-Hant
    6. 5. zh
    7. 6. (default)
    Parameters:
    • language_tags — (iterable) language tags
    • default_range

      (optional, None or str)

      If Lookup finds no match using the ranges in the header, and this argument is not None, Lookup will next attempt to match the range in this argument, using the same subtag truncation.
      default_range cannot be ‘‘, as ‘‘ is skipped in Lookup. See note.
      This parameter corresponds to the functionality described in RFC 4647, section 3.4.1, in the paragraph starting with “One common way to provide for a default is to allow a specific language range to be set as the default…”
    • default_tag

      (optional, None or str)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If Lookup finds no match using the ranges in the header and default_range, this argument is not None, and it does not match any range in the header with q=0 (exactly, with no subtag truncation), then this value is returned.
      This parameter corresponds to “return a particular language tag designated for the operation”, one of the examples of “defaulting behavior” described in RFC 4647, section 3.4.1.
    • default

      (optional, None or any type, including a callable)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If Lookup finds no match using the ranges in the header and default_range, and default_tag is None or not acceptable because it matches a q=0 range in the header, then Lookup will next examine the default argument.
      If default is a callable, it will be called, and the callable’s return value will be returned.
      If default is not a callable, the value itself will be returned.
      The difference between supplying a str to default_tag and default is that default_tag is checked against q=0 ranges in the header to see if it matches one of the ranges specified as not acceptable, whereas a str for the default argument is simply returned.
      This parameter corresponds to the “defaulting behavior” described in RFC 4647, section 3.4.1
    Returns:

    (str, None, or any type)

    The best match according to the Lookup matching scheme, or a return value from one of the default arguments.

    Notes:

    • Lookup’s behaviour with ‘*‘ language ranges in the header may be surprising. From RFC 4647, section 3.4:

      In the lookup scheme, this range does not convey enough information by itself to determine which language tag is most appropriate, since it matches everything. If the language range “*“ is followed by other language ranges, it is skipped. If the language range “*“ is the only one in the language priority list or if no other language range follows, the default value is computed and returned.

      So

      1. >>> header = AcceptLanguageValidHeader('de, zh, *')
      2. >>> header.lookup(language_tags=['ja', 'en'], default='default')
      3. 'default'
    • Any tags in language_tags and default_tag and any tag matched during the subtag truncation search for default_range, that are an exact match for a non-* range with q=0 in the header, are considered not acceptable and ruled out.

    • If there is a *;q=0 in the header, then default_range and default_tag have no effect, as *;q=0 means that all languages not already matched by other ranges within the header are unacceptable.

  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future.

    AcceptLanguageValidHeader.quality() uses its own algorithm (one not specified in RFC 7231) to determine what is a best match. The algorithm has many issues, and does not conform to RFC 7231.

    What should be considered a match depends on the needs of your application (for example, should a language range in the header match a more specific language tag offer, or a less specific tag offer?) RFC 7231, section 5.3.5 suggests three matching schemes from RFC 4647, two of which WebOb supports with AcceptLanguageValidHeader.basic_filtering() and AcceptLanguageValidHeader.lookup() (we interpret the RFC to mean that Extended Filtering cannot apply for the Accept-Language header, as the header only accepts basic language ranges.) AcceptLanguageValidHeader.basic_filtering() returns quality values with the matched language tags. AcceptLanguageValidHeader.lookup() returns a language tag without the quality value, but the quality value is less likely to be useful when we are looking for a best match.

    If these are not suitable or sufficient for the needs of your application, you may need to write your own matching using AcceptLanguageValidHeader.parsed.

    Parameters:offer — (str) language tag offer
    Returns:(float or None)
    The highest quality value from the language range(s) that match the offer, or None if there is no match.

    Issues:

    • Incorrect handling of q=0 and *:

      1. >>> header = AcceptLanguageValidHeader(header_value='en;q=0, *')
      2. >>> header.quality(offer='en')
      3. 1.0
    • Matching only takes into account the first subtag when matching a range with more specific or less specific tags:

      1. >>> header = AcceptLanguageValidHeader(header_value='zh')
      2. >>> header.quality(offer='zh-Hans-CN')
      3. 1.0
      4. >>> header = AcceptLanguageValidHeader(header_value='zh-Hans')
      5. >>> header.quality(offer='zh-Hans-CN')
      6. >>> header.quality(offer='zh-Hans-CN') is None
      7. True
      8. >>> header = AcceptLanguageValidHeader(header_value='zh-Hans-CN')
      9. >>> header.quality(offer='zh')
      10. 1.0
      11. >>> header.quality(offer='zh-Hans')
      12. >>> header.quality(offer='zh-Hans') is None
      13. True
  • classmethod parse(value)

    Parse an Accept-Language header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Language header, returns an iterator of (language range, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header

class webob.acceptparse.AcceptLanguageNoHeader

Represent when there is no Accept-Language header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptLanguageNoHeader.__add__()).

  • __init__()

    Create an AcceptLanguageNoHeader instance.

  • header_value

    (str or None) The header value.

    As there is no header in the request, this is None.

  • parsed

    (list or None) Parsed form of the header.

    As there is no header in the request, this is None.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    If other is a valid header value or an AcceptLanguageValidHeader instance, a new AcceptLanguageValidHeader instance with the valid header value is returned.

    If other is None, an AcceptLanguageNoHeader instance, an invalid header value, or an AcceptLanguageInvalidHeader instance, a new AcceptLanguageNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptLanguageNoHeader.__add__().

  • __str__()

    Return the str '<no header in request>'.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the AcceptLanguage classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) language tag offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Language header in the request, or the header is invalid, so any language tag is acceptable, and this always returns True.

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the language ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    For this class, either there is no Accept-Language header in the request, or the header is invalid, so there are no language ranges, and this always returns an empty iterator.

  • basic_filtering(language_tags)

    Return the tags that match the header, using Basic Filtering.

    Parameters:language_tags — (iterable) language tags
    Returns:A list of tuples of the form (language tag, qvalue), in descending order of preference.

    When the header is invalid and when the header is not in the request, there are no matches, so this method always returns an empty list.

  • best_match(offers, default_match=None)

    Return the best match from the sequence of language tag offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptLanguageValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptLanguageValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Language header in the request, any of the language tags in offers are considered acceptable, so the best match is the tag in offers with the highest server quality value (if the server quality value is not supplied, it is 1).

    If more than one language tags in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str language tag, or a (language tag, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The language tag that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • lookup(language_tags=None, default_range=None, default_tag=None, default=None)

    Return the language tag that best matches the header, using Lookup.

    When the header is invalid, or there is no Accept-Language header in the request, all language tags are considered acceptable, so it is as if the header is ‘*‘. As specified for the Lookup matching scheme in RFC 4647, section 3.4, when the header is ‘*‘, the default value is to be computed and returned. So this method will ignore the language_tags and default_range arguments, and proceed to default_tag, then default.

    Parameters:
    • language_tags

      (optional, any type)

      This argument is ignored, and is only used as a placeholder so that the method signature corresponds to that of AcceptLanguageValidHeader.lookup().
    • default_range

      (optional, any type)

      This argument is ignored, and is only used as a placeholder so that the method signature corresponds to that of AcceptLanguageValidHeader.lookup().
    • default_tag

      (optional, None or str)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If this argument is not None, then it is returned.
      This parameter corresponds to “return a particular language tag designated for the operation”, one of the examples of “defaulting behavior” described in RFC 4647, section 3.4.1.
    • default

      (optional, None or any type, including a callable)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If default_tag is None, then Lookup will next examine the default argument.
      If default is a callable, it will be called, and the callable’s return value will be returned.
      If default is not a callable, the value itself will be returned.
      This parameter corresponds to the “defaulting behavior” described in RFC 4647, section 3.4.1
    Returns:

    (str, or any type)

    the return value from default_tag or default.

  • classmethod parse(value)

    Parse an Accept-Language header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Language header, returns an iterator of (language range, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptLanguageValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptLanguageValidHeader.quality()).

    Parameters:offer — (str) language tag offer
    Returns:(float) 1.0.

    When the Accept-Language header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

class webob.acceptparse.AcceptLanguageInvalidHeader(header_value)

Represent an invalid Accept-Language header.

An invalid header is one that does not conform to RFC 7231#section-5.3.5. As specified in the RFC, an empty header is an invalid Accept-Language header.

RFC 7231 does not provide any guidance on what should happen if the Accept-Language header has an invalid value. This implementation disregards the header, and treats it as if there is no Accept-Language header in the request.

This object should not be modified. To add to the header, we can use the addition operators (+ and +=), which return a new object (see the docstring for AcceptLanguageInvalidHeader.__add__()).

  • __init__(header_value)

    Create an AcceptLanguageInvalidHeader instance.

  • header_value

    (str or None) The header value.

  • parsed

    (list or None) Parsed form of the header.

    As the header is invalid and cannot be parsed, this is None.

  • __add__(other)

    Add to header, creating a new header object.

    other can be:

    If other is a valid header value or an AcceptLanguageValidHeader instance, a new AcceptLanguageValidHeader instance with the valid header value is returned.

    If other is None, an AcceptLanguageNoHeader instance, an invalid header value, or an AcceptLanguageInvalidHeader instance, a new AcceptLanguageNoHeader instance is returned.

  • __radd__(other)

    Add to header, creating a new header object.

    See the docstring for AcceptLanguageValidHeader.__add__().

  • __str__()

    Return the str '<invalid header value>'.

  • __contains__(offer)

    Return bool indicating whether offer is acceptable.

    Warning

    The behavior of .__contains__ for the AcceptLanguage classes is currently being maintained for backward compatibility, but it will change in the future to better conform to the RFC.

    Parameters:offer — (str) language tag offer
    Returns:(bool) Whether offer is acceptable according to the header.

    For this class, either there is no Accept-Language header in the request, or the header is invalid, so any language tag is acceptable, and this always returns True.

  • __iter__()

    Return all the ranges with non-0 qvalues, in order of preference.

    Warning

    The behavior of this method is currently maintained for backward compatibility, but will change in the future.

    Returns:iterator of all the language ranges in the header with non-0 qvalues, in descending order of qvalue. If two ranges have the same qvalue, they are returned in the order of their positions in the header, from left to right.

    For this class, either there is no Accept-Language header in the request, or the header is invalid, so there are no language ranges, and this always returns an empty iterator.

  • basic_filtering(language_tags)

    Return the tags that match the header, using Basic Filtering.

    Parameters:language_tags — (iterable) language tags
    Returns:A list of tuples of the form (language tag, qvalue), in descending order of preference.

    When the header is invalid and when the header is not in the request, there are no matches, so this method always returns an empty list.

  • best_match(offers, default_match=None)

    Return the best match from the sequence of language tag offers.

    This is the .best_match() method for when the header is invalid or not found in the request, corresponding to AcceptLanguageValidHeader.best_match().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptLanguageValidHeader.best_match()).

    When the header is invalid, or there is no Accept-Language header in the request, any of the language tags in offers are considered acceptable, so the best match is the tag in offers with the highest server quality value (if the server quality value is not supplied, it is 1).

    If more than one language tags in offers have the same highest server quality value, then the one that shows up first in offers is the best match.

    Parameters:
    • offers

      (iterable)

      Each item in the iterable may be a str language tag, or a (language tag, server quality value) tuple or list. (The two may be mixed in the iterable.)
    • default_match — (optional, any type) the value to be returned if offers is empty.
    Returns:

    (str, or the type of default_match)

    The language tag that has the highest server quality value. If offers is empty, the value of default_match is returned.

  • lookup(language_tags=None, default_range=None, default_tag=None, default=None)

    Return the language tag that best matches the header, using Lookup.

    When the header is invalid, or there is no Accept-Language header in the request, all language tags are considered acceptable, so it is as if the header is ‘*‘. As specified for the Lookup matching scheme in RFC 4647, section 3.4, when the header is ‘*‘, the default value is to be computed and returned. So this method will ignore the language_tags and default_range arguments, and proceed to default_tag, then default.

    Parameters:
    • language_tags

      (optional, any type)

      This argument is ignored, and is only used as a placeholder so that the method signature corresponds to that of AcceptLanguageValidHeader.lookup().
    • default_range

      (optional, any type)

      This argument is ignored, and is only used as a placeholder so that the method signature corresponds to that of AcceptLanguageValidHeader.lookup().
    • default_tag

      (optional, None or str)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If this argument is not None, then it is returned.
      This parameter corresponds to “return a particular language tag designated for the operation”, one of the examples of “defaulting behavior” described in RFC 4647, section 3.4.1.
    • default

      (optional, None or any type, including a callable)

      At least one of default_tag or default must be supplied as an argument to the method, to define the defaulting behaviour.
      If default_tag is None, then Lookup will next examine the default argument.
      If default is a callable, it will be called, and the callable’s return value will be returned.
      If default is not a callable, the value itself will be returned.
      This parameter corresponds to the “defaulting behavior” described in RFC 4647, section 3.4.1
    Returns:

    (str, or any type)

    the return value from default_tag or default.

  • classmethod parse(value)

    Parse an Accept-Language header.

    Parameters:value — (str) header value
    Returns:If value is a valid Accept-Language header, returns an iterator of (language range, quality value) tuples, as parsed from the header from left to right.
    Raises:ValueError — if value is an invalid header
  • quality(offer)

    Return quality value of given offer, or None if there is no match.

    This is the .quality() method for when the header is invalid or not found in the request, corresponding to AcceptLanguageValidHeader.quality().

    Warning

    This is currently maintained for backward compatibility, and will be deprecated in the future (see the documentation for AcceptLanguageValidHeader.quality()).

    Parameters:offer — (str) language tag offer
    Returns:(float) 1.0.

    When the Accept-Language header is invalid or not in the request, all offers are equally acceptable, so 1.0 is always returned.

Deprecated:

class webob.acceptparse.MIMEAccept(header_value)

Backwards compatibility shim for the new functionality provided by AcceptValidHeader, AcceptInvalidHeader, or AcceptNoHeader, that acts like the old MIMEAccept from WebOb version 1.7 or lower.

This shim does use the newer Accept header parsing, which will mean your application may be less liberal in what Accept headers are correctly parsed. It is recommended that user agents be updated to send appropriate Accept headers that are valid according to rfc:RFC 7231, section 5.3.2 <7231#section-5.3.2>

Deprecated since version 1.8: Instead of directly creating the Accept object, please see: create_accept_header(header_value), which will create the appropriate object.

This shim has an extended deprecation period to allow for application developers to switch the to new API.

Cache-Control

class webob.cachecontrol.CacheControl(properties, type)

Represents the Cache-Control header.

By giving a type of 'request' or 'response' you can control what attributes are allowed (some Cache-Control values only apply to requests or responses).

  • update_dict

    alias of UpdateDict

  • classmethod parse(header, updates_to=None, type=None)

    Parse the header, returning a CacheControl object.

    The object is bound to the request or response object updates_to, if that is given.

  • copy()

    Returns a copy of this object.

class webob.byterange.Range(start, end)

Represents the Range header.

  • range_for_length(length)

    If there is only one range, and if it is satisfiable by the given length, then return a (start, end) non-inclusive range of bytes to serve. Otherwise return None

  • content_range(length)

    Works like range_for_length; returns None or a ContentRange object

    You can use it like:

    1. response.content_range = req.range.content_range(response.content_length)

    Though it’s still up to you to actually serve that content range!

  • classmethod parse(header)

    Parse the header; may return None if header is invalid

class webob.byterange.ContentRange(start, stop, length)

Represents the Content-Range header

This header is start-stop/length, where start-stop and length can be * (represented as None in the attributes).

  • classmethod parse(value)

    Parse the header. May return None if it cannot parse.

class webob.etag.IfRange(etag)

  • classmethod parse(value)

    Parse this from a header value.

ETag

class webob.etag.ETagMatcher(etags)

  • classmethod parse(value, strong=True)

    Parse this from a header value

Misc Functions and Internals

webob.html_escape(s)

HTML-escape a string or object

This converts any non-string objects passed into it to strings (actually, using unicode()). All values returned are non-unicode strings (using &#num; entities for all non-ASCII characters).

None is treated specially, and returns the empty string.

class webob.headers.ResponseHeaders(\args, **kw*)

Dictionary view on the response headerlist. Keys are normalized for case and whitespace.

  • getall(key)

    Return a list of all values matching the key (may be an empty list)

  • mixed()

    Returns a dictionary where the values are either single values, or a list of values when a key/value appears more than once in this dictionary. This is similar to the kind of dictionary often used to represent the variables in a web request.

  • dict_of_lists()

    Returns a dictionary where each key is associated with a list of values.

  • setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D

  • pop(k[, d]) → v, remove specified key and return the corresponding value.

    If key is not found, d is returned if given, otherwise KeyError is raised.

class webob.headers.EnvironHeaders(environ)

An object that represents the headers as present in a WSGI environment.

This object is a wrapper (with no internal state) for a WSGI request object, representing the CGI-style HTTP_* keys as a dictionary. Because a CGI environment can only hold one value for each key, this dictionary is single-valued (unlike outgoing headers).

  • keys() → a set-like object providing a view on D’s keys

class webob.cachecontrol.UpdateDict

Dict that has a callback on all updates

  • clear() → None. Remove all items from D.

  • update([E, ]\*F*) → None. Update D from dict/iterable E and F.

    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

  • setdefault(key, value=None)

    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

  • pop(k[, d]) → v, remove specified key and return the corresponding value.

    If key is not found, d is returned if given, otherwise KeyError is raised

  • popitem() → (k, v), remove and return some (key, value) pair as a

    2-tuple; but raise KeyError if D is empty.