Added DynamicSchemaMixin class to allow definition of schema name from configuration
authorThierry Florac <thierry.florac@onf.fr>
Wed, 01 Jul 2015 10:15:10 +0200
changeset 9 d114654e7423
parent 8 41d8e2491ec9
child 10 d775bab6f983
Added DynamicSchemaMixin class to allow definition of schema name from configuration
src/pyams_alchemy/mixin.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_alchemy/mixin.py	Wed Jul 01 10:15:10 2015 +0200
@@ -0,0 +1,49 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# 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.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+
+# import packages
+from pyramid.threadlocal import get_current_registry
+from sqlalchemy.ext.declarative import declared_attr
+from zope.component.globalregistry import getGlobalSiteManager
+
+
+class DynamicSchemaMixin(object):
+    """Dynamic schema mixin class
+
+    This class is used to set an entity schema name in Pyramid settings
+    """
+
+    __schema__ = None
+
+    @classmethod
+    def get_schema_settings_name(cls):
+        return 'pyams_alchemy:{0}.{1}.schema'.format(cls.__module__, cls.__name__)
+
+    @classmethod
+    def get_schema(cls):
+        settings_name = cls.get_schema_settings_name()
+        if settings_name:
+            registry = get_current_registry() or getGlobalSiteManager()
+            return {'schema': registry.settings.get(settings_name, cls.__schema__)}
+        else:
+            return {'schema': cls.__schema__}
+
+    @declared_attr
+    def __table_args__(cls):
+        return cls.get_schema()