Package lastfm :: Module decorators

[hide private]
[frames] | no frames]

# Source Code for Module lastfm.decorators

      1  #!/usr/bin/env python
      2  """Module containting the decorators used in the package"""
      3
      4  __author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>"
      5  __version__ = "0.2"
      6  __license__ = "GNU Lesser General Public License"
      7
      8 -def top_property(list_property_name):
      9      """
     10      A decorator to return a property that returns the first value of list
     11      attribute corresponding to the provided list property name.
     12
     13      For example, if the list property is top_albums, then the decorator returns
     14      a property that returns the first (top most) album.
     15
     16      @param list_property_name: the name of the list property. Like 'top_albums'.
     17      @type list_property_name:  L{str}
     18
     19      @return:                   a property that returns the first value of list attribute
     20                                 corresponding to the provided list property name
     21      @rtype:                    L{property}
     22      """
     23      def decorator(func):
     24          def wrapper(ob):
     25              top_list = getattr(ob, list_property_name)
     26              return (len(top_list) and top_list[0] or None)
     27          return property(fget = wrapper, doc = func.__doc__)
     28      return decorator
     29
     30 -def cached_property(func):
     31      """
     32      A decorator to cache the atrribute of the object. When called for the first time,
     33      the value of the attribute is retrived and saved in an instance variable. Later
     34      calls return the copy of the cached value, so that the original cached value
     35      cannot be modified.
     36
     37      @param func:  the getter function of the attribute
     38      @type func:   C{function}
     39
     40      @return:      a property that wraps the getter function of the attribute
     41      @rtype:       L{property}
     42      """
     43      func_name = func.func_code.co_name
     44      attribute_name = "_%s" % func_name
     45
     46      def wrapper(ob):
     47          cache_attribute = getattr(ob, attribute_name, None)
     48          if cache_attribute is None:
     49              cache_attribute = func(ob)
     50              setattr(ob, attribute_name, cache_attribute)
     51          try:
     52              cp = copy.copy(cache_attribute)
     53              return cp
     54          except LastfmError:
     55              return cache_attribute
     56
     57      return property(fget = wrapper, doc = func.__doc__)
     58
     59 -def authenticate(func):
     60      """
     61      A decorator to check if the current user is authenticated or not. Used only
     62      on the functions that need authentication. If not authenticated then an
     63      exception is raised.
     64
     65      @param func:    a function that needs to be authentication, for being called
     66      @type func:     C{function}
     67
     68      @return:        a function that wraps the original function
     69      @rtype:         C{function}
     70
     71      @raise AuthenticationFailedError: If the user is not authenticated, then an
     72                                        exception is raised.
     73      """
     74      def wrapper(self, *args, **kwargs):
     75          from lastfm.user import User, Api
     76          username = None
     77          if isinstance(self, User):
     78              username = self.name
     79              if self.authenticated:
     80                 return func(self, *args, **kwargs)
     81          elif hasattr(self, 'user'):
     82              username = self.user.name
     83              if self.user.authenticated:
     84                 return func(self, *args, **kwargs)
     85          elif hasattr(self, '_subject') and isinstance(self._subject, User):
     86              username = self._subject.name
     87              if self._subject.authenticated:
     88                  return func(self, *args, **kwargs)
     89          elif hasattr(self, '_api') and isinstance(self._api, Api):
     90              try:
     91                  user = self._api.get_authenticated_user()
     92                  username = user.name
     93                  return func(self, *args, **kwargs)
     94              except AuthenticationFailedError:
     95                  pass
     96          raise AuthenticationFailedError(
     97              "user '%s' does not have permissions to access the service" % username)
     98      return wrapper
     99
    100  import copy
    101  from lastfm.error import LastfmError, AuthenticationFailedError
    102