
    s
                     T    d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlm	Z
 d	dZy)
z0Common utilities for using the persistent cache.    )absolute_import)division)unicode_literalsN)	resources)
exceptionsc                       fd}|S )a  Decorator to cache the result of a function.

  The decorated function must return a resource.

  The returned function will take three arguments:
    cache: a Cache object.
    key: str, the key for the function call in the cache.
    args: tuple (optional), the arguments to pass to the original function. If
      not specified, key will be used.

  >>> @CacheResource('sums')
  ... def Add(value1, value2):
  ...   print 'adding...'
  ...   value = value1 + value2
  ...   return resources.REGISTRY.Parse(str(value), collection='...')
  >>> with cache_util.GetCache('resource://') as cache:
  ...   print Add(cache, '1+4', (1, 4))
  ...   print Add(cache, '1+4', (1, 4))
  adding...
  http://example.googleapis.com/v1/foos/5
  http://example.googleapis.com/v1/foos/5

  Args:
    table_prefix: str, a prefix for the names of the tables in the cache to use
      for these results
    timeout_sec: int, the time (in seconds) for which a table is valid

  Returns:
    function, a function that decorates with the appropriate behavior.
  c                 J     t        j                         d fd	       }|S )z'Wraps a function and caches its result.c                 p   dj                  	|      }| j                  |d
      }	 |j                         }|d   d   }t        j                  j                  |      S # t        j                  $ rB ||n|f} | }|j                  |j                         fg       |j                          |cY S w xY w)Nz{}:{}   )columnstimeoutr   )formatTableSelectr   REGISTRYParseURLcache_exceptionsCacheTableExpiredAddRowsSelfLinkValidate)cachekeyargs
table_nametableresulturlreffunctable_prefixtimeout_secs           1lib/googlecloudsdk/command_lib/util/cache_util.pyGetFromCachez4CacheResource.<locals>.Wrapper.<locals>.GetFromCache=   s    >>,4jkk*akEe
0 Qil!!**3// // 'tcVDk()*
s   A   AB54B5)N)	functoolswraps)r    r$   r!   r"   s   ` r#   WrapperzCacheResource.<locals>.Wrapper;   s&    __T0 0      )r!   r"   r'   s   `` r#   CacheResourcer*      s    >& 
.r(   )i:	 )__doc__
__future__r   r   r   r%   googlecloudsdk.corer   googlecloudsdk.core.cacher   r   r*   r)   r(   r#   <module>r/      s!     7 &  '  ) D2r(   