-
Notifications
You must be signed in to change notification settings - Fork 13
/
negotiator.py
61 lines (51 loc) · 2.11 KB
/
negotiator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Language Negotiator
"""
from zope.interface import implementer
from zope.i18n.interfaces import INegotiator
from zope.i18n.interfaces import IUserPreferredLanguages
def normalize_lang(lang):
lang = lang.strip().lower()
lang = lang.replace('_', '-')
lang = lang.replace(' ', '')
return lang
def normalize_langs(langs):
# Make a mapping from normalized->original so we keep can match
# the normalized lang and return the original string.
n_langs = {}
for lang in langs:
n_langs[normalize_lang(lang)] = lang
return n_langs
@implementer(INegotiator)
class Negotiator:
def getLanguage(self, langs, env):
envadapter = IUserPreferredLanguages(env)
userlangs = envadapter.getPreferredLanguages()
# Prioritize on the user preferred languages. Return the
# first user preferred language that the object has available.
langs = normalize_langs(langs)
for lang in userlangs:
if lang in langs:
return langs.get(lang)
# If the user asked for a specific variation, but we don't
# have it available we may serve the most generic one,
# according to the spec (eg: user asks for ('en-us',
# 'de'), but we don't have 'en-us', then 'en' is preferred
# to 'de').
parts = lang.split('-')
if len(parts) > 1 and parts[0] in langs:
return langs.get(parts[0])
return None
negotiator = Negotiator()