- """A tiny Session subclass that adds support for a default language."""
- default_language = 'en'
-
- def execute(self, clause, params=None, *args, **kwargs):
- if not params:
- params = {}
- params.setdefault('_default_language', self.default_language)
- return super(MultilangSession, self).execute(
- clause, params, *args, **kwargs)
+ """A tiny Session subclass that adds support for a default language.
+
+ Needs to be used with `MultilangScopedSession`, below.
+ """
+ default_language_id = None
+
+ def __init__(self, *args, **kwargs):
+ if 'default_language_id' in kwargs:
+ self.default_language_id = kwargs.pop('default_language_id')
+
+ super(MultilangSession, self).__init__(*args, **kwargs)
+
+ def connection(self, *args, **kwargs):
+ """Monkeypatch the connection. Not pretty at all.
+ """
+ conn = super(MultilangSession, self).connection(*args, **kwargs)
+ original_execute = conn.execute
+ if original_execute.__name__ != 'monkeypatched_execute':
+ def monkeypatched_execute(statement, *multiparams, **params):
+ if isinstance(statement, Select):
+ boundparams = dict(multiparams[0])
+ boundparams.setdefault('_default_language_id', self.default_language_id)
+ multiparams = [boundparams] + list(multiparams[1:])
+ return original_execute(statement, *multiparams, **params)
+ conn.execute = monkeypatched_execute
+ return conn
+
+class MultilangScopedSession(ScopedSession):
+ """Dispatches language selection to the attached Session."""
+
+ @property
+ def default_language_id(self):
+ """Passes the new default language id through to the current session.
+ """
+ return self.registry().default_language_id
+
+ @default_language_id.setter
+ def default_language_id(self, new):
+ self.registry().default_language_id = new