--- a/src/pyams_utils/session.py Wed Jul 12 13:55:47 2017 +0200
+++ b/src/pyams_utils/session.py Wed Jul 12 13:56:41 2017 +0200
@@ -18,6 +18,42 @@
# import interfaces
# import packages
+from pyams_utils.request import check_request
+
+
+_marker = object()
+
+
+def session_property(app, key=None, prefix=None):
+ """Define a method decorator used to store result into request's session
+
+ If no request is currently running, a new one is created.
+
+ :param str app: application identifier used to prefix session keys
+ :param str key: session's value key; if *None*, the key will be the method's object; if *key* is a callable
+ object, il will be called to get the actual session key
+ :param prefix: str; prefix to use for session key; if *None*, the prefix will be the property name
+ """
+
+ def session_decorator(func):
+
+ def wrapper(obj, app, key, *args, **kwargs):
+ request = check_request()
+ if callable(key):
+ key = key(obj, *args, **kwargs)
+ if not key:
+ key = '{1}::{0!r}'.format(obj, prefix or func.__name__)
+ data = get_session_data(request, app, key, _marker)
+ if data is _marker:
+ data = func
+ if callable(data):
+ data = data(obj, *args, **kwargs)
+ set_session_data(request, app, key, data)
+ return data
+
+ return lambda x, *args, **kwargs: wrapper(x, app, key, *args, **kwargs)
+
+ return session_decorator
def get_session_data(request, app, key, default=None):