"Fossies" - the Fresh Open Source Software Archive

Member "roundup-2.0.0/roundup/cgi/accept_language.py" (29 Feb 2020, 1889 Bytes) of package /linux/www/roundup-2.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "accept_language.py": 1.6.1_vs_2.0.0.

    1 """Parse the Accept-Language header as defined in RFC2616.
    2 
    3 See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    4 for details.  This module should follow the spec.
    5 Author: Hernan M. Foffani (hfoffani@gmail.com)
    6 Some use samples:
    7 
    8 >>> parse("da, en-gb;q=0.8, en;q=0.7")
    9 ['da', 'en_gb', 'en']
   10 >>> parse("en;q=0.2, fr;q=1")
   11 ['fr', 'en']
   12 >>> parse("zn; q = 0.2 ,pt-br;q =1")
   13 ['pt_br', 'zn']
   14 >>> parse("es-AR")
   15 ['es_AR']
   16 >>> parse("es-es-cat")
   17 ['es_es_cat']
   18 >>> parse("")
   19 []
   20 >>> parse(None)
   21 []
   22 >>> parse("   ")
   23 []
   24 >>> parse("en,")
   25 ['en']
   26 """
   27 
   28 import re
   29 import heapq
   30 
   31 # regexp for languange-range search
   32 nqlre = "([A-Za-z]+[-[A-Za-z]+]*)$"
   33 # regexp for languange-range search with quality value
   34 qlre = r"([A-Za-z]+[-[A-Za-z]+]*);q=([\d\.]+)"
   35 # both
   36 lre = re.compile(nqlre + "|" + qlre)
   37 
   38 whitespace = ' \t\n\r\v\f'
   39 try:
   40     # Python 3.
   41     remove_ws = (str.maketrans('', '', whitespace),)
   42 except AttributeError:
   43     # Python 2.
   44     remove_ws = (None, whitespace)
   45 
   46 
   47 def parse(language_header):
   48     """parse(string_with_accept_header_content) -> languages list"""
   49 
   50     if language_header is None: return []
   51 
   52     # strip whitespaces.
   53     lh = language_header.translate(*remove_ws)
   54 
   55     # if nothing, return
   56     if lh == "": return []
   57 
   58     # split by commas and parse the quality values.
   59     pls = [lre.findall(x) for x in lh.split(',')]
   60 
   61     # drop uncomformant
   62     qls = [x[0] for x in pls if len(x) > 0]
   63 
   64     # use a heap queue to sort by quality values.
   65     # the value of each item is 1.0 complement.
   66     pq = []
   67     for l in qls:
   68         if l[0] != '':
   69             heapq.heappush(pq, (0.0, l[0]))
   70         else:
   71             heapq.heappush(pq, (1.0-float(l[2]), l[1]))
   72 
   73     # get the languages ordered by quality
   74     # and replace - by _
   75     return [x[1].replace('-', '_') for x in pq]
   76 
   77 if __name__ == "__main__":
   78     import doctest
   79     doctest.testmod()
   80 
   81 # vim: set et sts=4 sw=4 :