--- a/src/pyams_utils/property.py Sun Feb 22 14:52:03 2015 +0100
+++ b/src/pyams_utils/property.py Sat Feb 28 16:18:26 2015 +0100
@@ -64,42 +64,53 @@
_marker = object()
-class request_property(object):
- """Define a property stored in request annotations"""
- def __init__(self, fget, key=None):
- self.fget = fget
- if key is None:
- key = "%s.%s" % (fget.__module__, fget.__name__)
- self.key = key
+def request_property(key):
+ """Define a method decorator used to store result into request's annotations
+
+ `key` is a required argument; if None, the key will be the method's object
+ """
- def __get__(self, obj, cls):
- if obj is None:
- return self
- request = check_request()
- data = get_request_data(request, self.key, _marker)
- if data is _marker:
- data = self.fget(obj)
- set_request_data(request, self.key, data)
- return data
+ def request_decorator(func):
+ def wrapper(obj, key, *args, **kwargs):
+ request = check_request()
+ if callable(key):
+ key = key(obj)
+ if not key:
+ key = '%r' % obj
+ data = get_request_data(request, key, _marker)
+ if data is _marker:
+ data = func
+ if callable(data):
+ data = data(obj, *args, **kwargs)
+ set_request_data(request, key, data)
+ return data
+ return lambda x: wrapper(x, key=key)
+
+ return request_decorator
-class session_property(object):
- """Define a property stored into session"""
+def session_property(app, key=None):
+ """Define a method decorator used to store result into request's session
- def __init__(self, fget, app, key=None):
- self.fget = fget
- self.app = app
- if key is None:
- key = "%s.%s" % (fget.__module__, fget.__name__)
- self.key = key
+ `app` is an application identifier used to prefix session keys
+ `key` is session's value key; if None, the key will be the method's object
+ """
- def __get__(self, obj, cls):
- if obj is None:
- return self
- request = check_request()
- data = get_session_data(request, self.app, self.key, _marker)
- if data is _marker:
- data = self.fget(obj)
- set_session_data(request, self.app, self.key, data)
- return data
+ def session_decorator(func):
+ def wrapper(obj, app, key, *args, **kwargs):
+ request = check_request()
+ if callable(key):
+ key = key(obj)
+ if not key:
+ key = '%r' % obj
+ 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: wrapper(x, app=app, key=key)
+
+ return session_decorator