dogpile.cache / dogpile / cache / region.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
from __future__ import with_statement
from dogpile.core import Lock, NeedRegenerationException
from dogpile.core.nameregistry import NameRegistry
from .util import function_key_generator, PluginLoader, \
    memoized_property, coerce_string_conf
from .api import NO_VALUE, CachedValue
from .proxy import ProxyBackend
from . import compat
import time
from functools import wraps
import threading

_backend_loader = PluginLoader("dogpile.cache")
register_backend = _backend_loader.register
from . import backends

value_version = 1
"""An integer placed in the :class:`.CachedValue`
so that new versions of dogpile.cache can detect cached
values from a previous, backwards-incompatible version.

"""

class CacheRegion(object):
    """A front end to a particular cache backend.

    :param name: Optional, a string name for the region.
     This isn't used internally
     but can be accessed via the ``.name`` parameter, helpful
     for configuring a region from a config file.
    :param function_key_generator:  Optional.  A
     function that will produce a "cache key" given
     a data creation function and arguments, when using
     the :meth:`.CacheRegion.cache_on_arguments` method.
     The structure of this function
     should be two levels: given the data creation function,
     return a new function that generates the key based on
     the given arguments.  Such as::

        def my_key_generator(namespace, fn):
            fname = fn.__name__
            def generate_key(*arg):
                return namespace + "_" + fname + "_".join(str(s) for s in arg)
            return generate_key


        region = make_region(
            function_key_generator = my_key_generator
        ).configure(
            "dogpile.cache.dbm",
            expiration_time=300,
            arguments={
                "filename":"file.dbm"
            }
        )

     The ``namespace`` is that passed to
     :meth:`.CacheRegion.cache_on_arguments`.  It's not consulted
     outside this function, so in fact can be of any form.
     For example, it can be passed as a tuple, used to specify
     arguments to pluck from \**kw::

        def my_key_generator(namespace, fn):
            def generate_key(*arg, **kw):
                return ":".join(
                        [kw[k] for k in namespace] +
                        [str(x) for x in arg]
                    )

     Where the decorator might be used as::

        @my_region.cache_on_arguments(namespace=('x', 'y'))
        def my_function(a, b, **kw):
            return my_data()

    :param key_mangler: Function which will be used on all incoming
     keys before passing to the backend.  Defaults to ``None``,
     in which case the key mangling function recommended by
     the cache backend will be used.    A typical mangler
     is the SHA1 mangler found at :func:`.sha1_mangle_key`
     which coerces keys into a SHA1
     hash, so that the string length is fixed.  To
     disable all key mangling, set to ``False``.   Another typical
     mangler is the built-in Python function ``str``, which can be used
     to convert non-string or Unicode keys to bytestrings, which is
     needed when using a backend such as bsddb or dbm under Python 2.x
     in conjunction with Unicode keys.
    :param async_creation_runner:  A callable that, when specified,
     will be passed to and called by dogpile.lock when
     there is a stale value present in the cache.  It will be passed the
     mutex and is responsible releasing that mutex when finished.
     This can be used to defer the computation of expensive creator
     functions to later points in the future by way of, for example, a
     background thread, a long-running queue, or a task manager system
     like Celery.

     For a specific example using async_creation_runner, new values can
     be created in a background thread like so::

        import threading

        def async_creation_runner(cache, somekey, creator, mutex):
            ''' Used by dogpile.core:Lock when appropriate  '''
            def runner():
                try:
                    value = creator()
                    cache.set(somekey, value)
                finally:
                    mutex.release()

            thread = threading.Thread(target=runner)
            thread.start()


        region = make_region(
            async_creation_runner=async_creation_runner,
        ).configure(
            'dogpile.cache.memcached',
            expiration_time=5,
            arguments={
                'url': '127.0.0.1:11211',
                'distributed_lock': True,
            }
        )

     Remember that the first request for a key with no associated
     value will always block; async_creator will not be invoked.
     However, subsequent requests for cached-but-expired values will
     still return promptly.  They will be refreshed by whatever
     asynchronous means the provided async_creation_runner callable
     implements.

     By default the async_creation_runner is disabled and is set
     to ``None``.

     .. versionadded:: 0.4.2 added the async_creation_runner
        feature.

    """

    def __init__(self,
            name=None,
            function_key_generator=function_key_generator,
            key_mangler=None,
            async_creation_runner=None,
    ):
        """Construct a new :class:`.CacheRegion`."""
        self.name = name
        self.function_key_generator = function_key_generator
        if key_mangler:
            self.key_mangler = key_mangler
        else:
            self.key_mangler = None
        self._invalidated = None
        self.async_creation_runner = async_creation_runner

    def configure(self, backend,
            expiration_time=None,
            arguments=None,
            _config_argument_dict=None,
            _config_prefix=None,
            wrap=None
        ):
        """Configure a :class:`.CacheRegion`.

        The :class:`.CacheRegion` itself
        is returned.

        :param backend:   Required.  This is the name of the
         :class:`.CacheBackend` to use, and is resolved by loading
         the class from the ``dogpile.cache`` entrypoint.

        :param expiration_time:   Optional.  The expiration time passed
         to the dogpile system.  The :meth:`.CacheRegion.get_or_create`
         method as well as the :meth:`.CacheRegion.cache_on_arguments`
         decorator (though note:  **not** the :meth:`.CacheRegion.get`
         method) will call upon the value creation function after this
         time period has passed since the last generation.

        :param arguments: Optional.  The structure here is passed
         directly to the constructor of the :class:`.CacheBackend`
         in use, though is typically a dictionary.

        :param wrap: Optional.  A list of :class:`.ProxyBackend`
         classes and/or instances, each of which will be applied
         in a chain to ultimately wrap the original backend,
         so that custom functionality augmentation can be applied.

         .. versionadded:: 0.4.4

         .. seealso::

            :ref:`changing_backend_behavior`

         """

        if "backend" in self.__dict__:
            raise Exception(
                    "This region is already "
                    "configured with backend: %s"
                    % self.backend)
        backend_cls = _backend_loader.load(backend)
        if _config_argument_dict:
            self.backend = backend_cls.from_config_dict(
                _config_argument_dict,
                _config_prefix
            )
        else:
            self.backend = backend_cls(arguments or {})
        self.expiration_time = expiration_time
        if self.key_mangler is None:
            self.key_mangler = self.backend.key_mangler

        self._lock_registry = NameRegistry(self._create_mutex)

        if getattr(wrap,'__iter__', False):
            for wrapper in reversed(wrap):
                self.wrap(wrapper)

        return self

    def wrap(self, proxy):
        ''' Takes a ProxyBackend instance or class and wraps the
        attached backend. '''

        # if we were passed a type rather than an instance then
        # initialize it.
        if type(proxy) == type:
            proxy = proxy()

        if not issubclass(type(proxy), ProxyBackend):
            raise Exception("Type %s is not a valid ProxyBackend"
                    % type(proxy))

        self.backend = proxy.wrap(self.backend)


    def _mutex(self, key):
        return self._lock_registry.get(key)

    class _LockWrapper(object):
        """weakref-capable wrapper for threading.Lock"""
        def __init__(self):
            self.lock = threading.Lock()

        def acquire(self, wait=True):
            return self.lock.acquire(wait)

        def release(self):
            self.lock.release()

    def _create_mutex(self, key):
        mutex = self.backend.get_mutex(key)
        if mutex is not None:
            return mutex
        else:
            return self._LockWrapper()

    def invalidate(self):
        """Invalidate this :class:`.CacheRegion`.

        Invalidation works by setting a current timestamp
        (using ``time.time()``)
        representing the "minimum creation time" for
        a value.  Any retrieved value whose creation
        time is prior to this timestamp
        is considered to be stale.  It does not
        affect the data in the cache in any way, and is also
        local to this instance of :class:`.CacheRegion`.

        Once set, the invalidation time is honored by
        the :meth:`.CacheRegion.get_or_create` and
        :meth:`.CacheRegion.get` methods.

        .. versionadded:: 0.3.0

        """
        self._invalidated = time.time()

    def configure_from_config(self, config_dict, prefix):
        """Configure from a configuration dictionary
        and a prefix.

        Example::

            local_region = make_region()
            memcached_region = make_region()

            # regions are ready to use for function
            # decorators, but not yet for actual caching

            # later, when config is available
            myconfig = {
                "cache.local.backend":"dogpile.cache.dbm",
                "cache.local.arguments.filename":"/path/to/dbmfile.dbm",
                "cache.memcached.backend":"dogpile.cache.pylibmc",
                "cache.memcached.arguments.url":"127.0.0.1, 10.0.0.1",
            }
            local_region.configure_from_config(myconfig, "cache.local.")
            memcached_region.configure_from_config(myconfig,
                                                "cache.memcached.")

        """
        config_dict = coerce_string_conf(config_dict)
        return self.configure(
            config_dict["%sbackend" % prefix],
            expiration_time = config_dict.get(
                                "%sexpiration_time" % prefix, None),
            _config_argument_dict=config_dict,
            _config_prefix="%sarguments." % prefix
        )


    @memoized_property
    def backend(self):
        raise Exception("No backend is configured on this region.")

    def get(self, key, expiration_time=None, ignore_expiration=False):
        """Return a value from the cache, based on the given key.

        If the value is not present, the method returns the token
        ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from
        ``None`` to distinguish between a cached value of ``None``.

        By default, the configured expiration time of the
        :class:`.CacheRegion`, or alternatively the expiration
        time supplied by the ``expiration_time`` argument,
        is tested against the creation time of the retrieved
        value versus the current time (as reported by ``time.time()``).
        If stale, the cached value is ignored and the ``NO_VALUE``
        token is returned.  Passing the flag ``ignore_expiration=True``
        bypasses the expiration time check.

        .. versionchanged:: 0.3.0
           :meth:`.CacheRegion.get` now checks the value's creation time
           against the expiration time, rather than returning
           the value unconditionally.

        The method also interprets the cached value in terms
        of the current "invalidation" time as set by
        the :meth:`.invalidate` method.   If a value is present,
        but its creation time is older than the current
        invalidation time, the ``NO_VALUE`` token is returned.
        Passing the flag ``ignore_expiration=True`` bypasses
        the invalidation time check.

        .. versionadded:: 0.3.0
           Support for the :meth:`.CacheRegion.invalidate`
           method.

        :param key: Key to be retrieved. While it's typical for a key to be a
         string, it is ultimately passed directly down to the cache backend,
         before being optionally processed by the key_mangler function, so can
         be of any type recognized by the backend or by the key_mangler
         function, if present.

        :param expiration_time: Optional expiration time value
         which will supersede that configured on the :class:`.CacheRegion`
         itself.

         .. versionadded:: 0.3.0

        :param ignore_expiration: if ``True``, the value is returned
         from the cache if present, regardless of configured
         expiration times or whether or not :meth:`.invalidate`
         was called.

         .. versionadded:: 0.3.0

        """

        if self.key_mangler:
            key = self.key_mangler(key)
        value = self.backend.get(key)
        value = self._unexpired_value_fn(
                        expiration_time, ignore_expiration)(value)

        return value.payload

    def _unexpired_value_fn(self, expiration_time, ignore_expiration):
        if ignore_expiration:
            return lambda value: value
        else:
            if expiration_time is None:
                expiration_time = self.expiration_time

            current_time = time.time()

            def value_fn(value):
                if value is NO_VALUE:
                    return value
                elif expiration_time is not None and \
                      current_time - value.metadata["ct"] > expiration_time:
                    return NO_VALUE
                elif self._invalidated and \
                        value.metadata["ct"] < self._invalidated:
                    return NO_VALUE
                else:
                    return value

            return value_fn

    def get_multi(self, keys, expiration_time=None, ignore_expiration=False):
        """Return multiple values from the cache, based on the given keys.

        If the value is not present, the method returns the token
        ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from
        ``None`` to distinguish between a cached value of ``None``.

        By default, the configured expiration time of the
        :class:`.CacheRegion`, or alternatively the expiration
        time supplied by the ``expiration_time`` argument,
        is tested against the creation time of the retrieved
        value versus the current time (as reported by ``time.time()``).
        If stale, the cached value is ignored and the ``NO_VALUE``
        token is returned.  Passing the flag ``ignore_expiration=True``
        bypasses the expiration time check.

        .. versionadded:: 0.4.4

        """
        if self.key_mangler:
            keys = map(lambda key: self.key_mangler(key), keys)
        values = {}
        backend_values = self.backend.get_multi(keys)

        _unexpired_value_fn = self._unexpired_value_fn(
                            expiration_time, ignore_expiration)
        values = dict(
                    (key, value.payload if value is not NO_VALUE else value)
                    for key, value in
                    (
                        (key, _unexpired_value_fn(value))
                        for key, value in backend_values.items()
                    )
                )
        return values

    def get_or_create(self, key, creator, expiration_time=None,
                                should_cache_fn=None):
        """Return a cached value based on the given key.

        If the value does not exist or is considered to be expired
        based on its creation time, the given
        creation function may or may not be used to recreate the value
        and persist the newly generated value in the cache.

        If the creation function returns :const:`NO_VALUE`, nothing is cached.
        Note that if the returns `None`, `None` will be cached.

        Whether or not the function is used depends on if the
        *dogpile lock* can be acquired or not.  If it can't, it means
        a different thread or process is already running a creation
        function for this key against the cache.  When the dogpile
        lock cannot be acquired, the method will block if no
        previous value is available, until the lock is released and
        a new value available.  If a previous value
        is available, that value is returned immediately without blocking.

        If the :meth:`.invalidate` method has been called, and
        the retrieved value's timestamp is older than the invalidation
        timestamp, the value is unconditionally prevented from
        being returned.  The method will attempt to acquire the dogpile
        lock to generate a new value, or will wait
        until the lock is released to return the new value.

        .. versionchanged:: 0.3.0
          The value is unconditionally regenerated if the creation
          time is older than the last call to :meth:`.invalidate`.

        :param key: Key to be retrieved. While it's typical for a key to be a
         string, it is ultimately passed directly down to the cache backend,
         before being optionally processed by the key_mangler function, so can
         be of any type recognized by the backend or by the key_mangler
         function, if present.

        :param creator: function which creates a new value.
        :param expiration_time: optional expiration time which will overide
         the expiration time already configured on this :class:`.CacheRegion`
         if not None.   To set no expiration, use the value -1.

        :param should_cache_fn: optional callable function which will receive the
         value returned by the "creator", and will then return True or False,
         indicating if the value should actually be cached or not.  If it
         returns False, the value is still returned, but isn't cached.
         E.g.::

            def dont_cache_none(value):
                return value is not None

            value = region.get_or_create("some key",
                                create_value,
                                should_cache_fn=dont_cache_none)

         Above, the function returns the value of create_value() if
         the cache is invalid, however if the return value is None,
         it won't be cached.

         .. versionadded:: 0.4.3

        See also:

        :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create`
        to any function using a decorator.

        """
        if self.key_mangler:
            key = self.key_mangler(key)

        def get_value():
            value = self.backend.get(key)
            if value is NO_VALUE or \
                value.metadata['v'] != value_version or \
                    (self._invalidated and
                    value.metadata["ct"] < self._invalidated):
                raise NeedRegenerationException()
            return value.payload, value.metadata["ct"]

        def gen_value():
            created_value = creator()
            value = self._value(created_value)

            if not should_cache_fn or \
                    should_cache_fn(created_value):
                self.backend.set(key, value)

            return value.payload, value.metadata["ct"]

        if expiration_time is None:
            expiration_time = self.expiration_time

        if self.async_creation_runner:
            def async_creator(mutex):
                return self.async_creation_runner(self, key, creator, mutex)
        else:
            async_creator = None

        with Lock(
                self._mutex(key),
                gen_value,
                get_value,
                expiration_time,
                async_creator) as value:
            return value

    def _value(self, value):
        """Return a :class:`.CachedValue` given a value."""
        return CachedValue(value, {
                            "ct": time.time(),
                            "v": value_version
                        })

    def set(self, key, value):
        """Place a new value in the cache under the given key."""

        if self.key_mangler:
            key = self.key_mangler(key)
        self.backend.set(key, self._value(value))


    def set_multi(self, mapping):
        """Place new values in the cache under the given keys.

        .. versionadded:: 0.4.4

        """

        if self.key_mangler:
            mapping = dict((self.key_mangler(k), self._value(v))
                                for k, v in mapping.items())
        else:
            mapping = dict((k, self._value(v)) for k, v in mapping.items())
        self.backend.set_multi(mapping)


    def delete(self, key):
        """Remove a value from the cache.

        This operation is idempotent (can be called multiple times, or on a
        non-existent key, safely)
        """

        if self.key_mangler:
            key = self.key_mangler(key)

        self.backend.delete(key)


    def delete_multi(self, keys):
        """Remove multiple values from the cache.

        This operation is idempotent (can be called multiple times, or on a
        non-existent key, safely)

        .. versionadded:: 0.4.4

        """

        if self.key_mangler:
            keys = map(lambda key: self.key_mangler(key), keys)

        self.backend.delete_multi(keys)


    def cache_on_arguments(self, namespace=None, expiration_time=None,
                                        should_cache_fn=None):
        """A function decorator that will cache the return
        value of the function using a key derived from the
        function itself and its arguments.

        The decorator internally makes use of the
        :meth:`.CacheRegion.get_or_create` method to access the
        cache and conditionally call the function.  See that
        method for additional behavioral details.

        E.g.::

            @someregion.cache_on_arguments()
            def generate_something(x, y):
                return somedatabase.query(x, y)

        The decorated function can then be called normally, where
        data will be pulled from the cache region unless a new
        value is needed::

            result = generate_something(5, 6)

        The function is also given an attribute ``invalidate``, which
        provides for invalidation of the value.  Pass to ``invalidate()``
        the same arguments you'd pass to the function itself to represent
        a particular value::

            generate_something.invalidate(5, 6)

        Another attribute ``set`` is added to provide extra caching
        possibilities relative to the function.   This is a convenience
        method for :meth:`.CacheRegion.set` which will store a given
        value directly without calling the decorated function.
        The value to be cached is passed as the first argument, and the
        arguments which would normally be passed to the function
        should follow::

            generate_something.set(3, 5, 6)

        The above example is equivalent to calling ``generate_something(5, 6)``,
        if the function were to produce the value ``3`` as the value to be
        cached.

        .. versionadded:: 0.4.1 Added set() method to decorated function.

        The default key generation will use the name
        of the function, the module name for the function,
        the arguments passed, as well as an optional "namespace"
        parameter in order to generate a cache key.

        Given a function ``one`` inside the module
        ``myapp.tools``::

            @region.cache_on_arguments(namespace="foo")
            def one(a, b):
                return a + b

        Above, calling ``one(3, 4)`` will produce a
        cache key as follows::

            myapp.tools:one|foo|3 4

        The key generator will ignore an initial argument
        of ``self`` or ``cls``, making the decorator suitable
        (with caveats) for use with instance or class methods.
        Given the example::

            class MyClass(object):
                @region.cache_on_arguments(namespace="foo")
                def one(self, a, b):
                    return a + b

        The cache key above for ``MyClass().one(3, 4)`` will
        again produce the same cache key of ``myapp.tools:one|foo|3 4`` -
        the name ``self`` is skipped.

        The ``namespace`` parameter is optional, and is used
        normally to disambiguate two functions of the same
        name within the same module, as can occur when decorating
        instance or class methods as below::

            class MyClass(object):
                @region.cache_on_arguments(namespace='MC')
                def somemethod(self, x, y):
                    ""

            class MyOtherClass(object):
                @region.cache_on_arguments(namespace='MOC')
                def somemethod(self, x, y):
                    ""

        Above, the ``namespace`` parameter disambiguates
        between ``somemethod`` on ``MyClass`` and ``MyOtherClass``.
        Python class declaration mechanics otherwise prevent
        the decorator from having awareness of the ``MyClass``
        and ``MyOtherClass`` names, as the function is received
        by the decorator before it becomes an instance method.

        The function key generation can be entirely replaced
        on a per-region basis using the ``function_key_generator``
        argument present on :func:`.make_region` and
        :class:`.CacheRegion`. If defaults to
        :func:`.function_key_generator`.

        :param namespace: optional string argument which will be
         established as part of the cache key.   This may be needed
         to disambiguate functions of the same name within the same
         source file, such as those
         associated with classes - note that the decorator itself
         can't see the parent class on a function as the class is
         being declared.
        :param expiration_time: if not None, will override the normal
         expiration time.

         May be specified as a callable, taking no arguments, that
         returns a value to be used as the ``expiration_time``. This callable
         will be called whenever the decorated function itself is called, in
         caching or retrieving. Thus, this can be used to
         determine a *dynamic* expiration time for the cached function
         result.  Example use cases include "cache the result until the
         end of the day, week or time period" and "cache until a certain date
         or time passes".

         .. versionchanged:: 0.4.4
            ``expiration_time`` may be passed as a callable to
            :meth:`.CacheRegion.cache_on_arguments`.

        :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`.

          .. versionadded:: 0.4.3

        """
        expiration_time_is_callable = compat.callable(expiration_time)
        def decorator(fn):
            key_generator = self.function_key_generator(namespace, fn)
            @wraps(fn)
            def decorate(*arg, **kw):
                key = key_generator(*arg, **kw)
                @wraps(fn)
                def creator():
                    return fn(*arg, **kw)
                timeout = expiration_time() if expiration_time_is_callable \
                            else expiration_time
                return self.get_or_create(key, creator, timeout,
                                          should_cache_fn)

            def invalidate(*arg, **kw):
                key = key_generator(*arg, **kw)
                self.delete(key)

            def set_(value, *arg, **kw):
                key = key_generator(*arg, **kw)
                self.set(key, value)

            decorate.set = set_
            decorate.invalidate = invalidate

            return decorate
        return decorator

def make_region(*arg, **kw):
    """Instantiate a new :class:`.CacheRegion`.

    Currently, :func:`.make_region` is a passthrough
    to :class:`.CacheRegion`.  See that class for
    constructor arguments.

    """
    return CacheRegion(*arg, **kw)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.