src/pyams_i18n/attr.py
changeset 9 017ad36cc2ba
parent 2 a44a73ee12f9
child 80 e431dcf09302
--- a/src/pyams_i18n/attr.py	Wed May 20 12:25:29 2015 +0200
+++ b/src/pyams_i18n/attr.py	Wed Jun 17 09:57:04 2015 +0200
@@ -16,10 +16,13 @@
 # import standard library
 
 # import interfaces
+from pyams_i18n.interfaces import II18n, INegotiator
 from zope.traversing.interfaces import ITraversable
 
 # import packages
-from pyams_utils.adapter import ContextAdapter, adapter_config
+from pyams_utils.adapter import adapter_config, ContextAdapter
+from pyams_utils.registry import query_utility
+from pyams_utils.request import check_request
 from pyramid.exceptions import NotFound
 from zope.interface import Interface
 
@@ -34,3 +37,33 @@
             return getattr(self.context, attr, {}).get(lang)
         except AttributeError:
             raise NotFound
+
+
+@adapter_config(context=Interface, provides=II18n)
+class I18nAttributeAdapter(ContextAdapter):
+    """I18n attribute adapter"""
+
+    def get_attribute(self, attribute, lang=None, request=None, default=None):
+        result = getattr(self.context, attribute)
+        if not isinstance(result, dict):
+            return default
+        if lang is None:
+            if request is None:
+                request = check_request()
+            lang = request.locale_name
+        return result.get(lang, default)
+
+    def query_attribute(self, attribute, lang=None, request=None):
+        result = getattr(self.context, attribute)
+        if not isinstance(result, dict):
+            return result
+        if lang is None:
+            if request is None:
+                request = check_request()
+            lang = request.locale_name
+        value = result.get(lang)
+        if not value:
+            negotiator = query_utility(INegotiator)
+            if (negotiator is not None) and (negotiator.server_language != lang):
+                value = result.get(negotiator.server_language)
+        return value