:param str directory: cache directory
:param int shards: number of shards to distribute writes
:param float timeout: SQLite connection timeout
:param disk: `Disk` instance for serialization
:param settings: any of `DEFAULT_SETTINGS`
def __getattr__(self, name):
safe_names = {'timeout', 'disk'}
valid_name = name in DEFAULT_SETTINGS or name in safe_names assert valid_name, 'cannot access {} in cache shard'.format(name) return getattr(self._shards[0], name)
@cl.contextmanager def transact(self, retry=True): """Context manager to perform a transaction by locking the cache.
While the cache is locked, no other write operation is permitted.
Transactions should therefore be as short as possible. Read and write
operations performed in a transaction are atomic. Read operations may
occur concurrent to a transaction.
Transactions may be nested and may not be shared between threads.
Blocks until transactions are held on all cache shards by retrying as
necessary.
>>> cache = FanoutCache()
>>> with cache.transact(): # Atomically increment two keys.
... _ = cache.incr('total', 123.4)
... _ = cache.incr('count', 1)
>>> with cache.transact(): # Atomically calculate average.
... average = cache['total'] / cache['count']
>>> average
123.4
:return: context manager for use in `with` statement
""" assert retry, 'retry must be True in FanoutCache' with cl.ExitStack() as stack: for shard in self._shards:
shard_transaction = shard.transact(retry=True)
stack.enter_context(shard_transaction) yield
def set(self, key, value, expire=None, read=False, tag=None, retry=False): """Set `key` and `value` item in cache.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param key: key for item
:param value: value for item
:param float expire: seconds until the key expires
(default None, no expiry)
:param bool read: read value as raw bytes from file (default False)
:param str tag: text to associate with key (default None)
:param bool retry: retry if database timeout occurs (default False)
:return: Trueif item was set
def add(self, key, value, expire=None, read=False, tag=None, retry=False): """Add `key` and `value` item to cache.
Similar to `set`, but only add to cache if key not present.
This operation is atomic. Only one concurrent add operation for given
key from separate threads or processes will succeed.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param key: key for item
:param value: value for item
:param float expire: seconds until the key expires
(default None, no expiry)
:param bool read: read value as bytes from file (default False)
:param str tag: text to associate with key (default None)
:param bool retry: retry if database timeout occurs (default False)
:return: Trueif item was added
def incr(self, key, delta=1, default=0, retry=False): """Increment value by delta for item with key.
If key is missing and default isNone then raise KeyError. Elseif key is missing and default isnotNone then use default for value.
Operation is atomic. All concurrent increment operations will be
counted individually.
Assumes value may be stored in a SQLite column. Most builds that target
machines with 64-bit pointer widths will support 64-bit signed
integers.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param key: key for item
:param int delta: amount to increment (default 1)
:param int default: value if key is missing (default 0)
:param bool retry: retry if database timeout occurs (default False)
:return: new value for item on success elseNone
:raises KeyError: if key isnot found and default isNone
def decr(self, key, delta=1, default=0, retry=False): """Decrement value by delta for item with key.
If key is missing and default isNone then raise KeyError. Elseif key is missing and default isnotNone then use default for value.
Operation is atomic. All concurrent decrement operations will be
counted individually.
Unlike Memcached, negative values are supported. Value may be
decremented below zero.
Assumes value may be stored in a SQLite column. Most builds that target
machines with 64-bit pointer widths will support 64-bit signed
integers.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param key: key for item
:param int delta: amount to decrement (default 1)
:param int default: value if key is missing (default 0)
:param bool retry: retry if database timeout occurs (default False)
:return: new value for item on success elseNone
:raises KeyError: if key isnot found and default isNone
def get(
self,
key,
default=None,
read=False,
expire_time=False,
tag=False,
retry=False,
): """Retrieve value from cache. If `key` is missing, return `default`.
If database timeout occurs then returns `default` unless `retry` is set
to `True` (default `False`).
:param key: key for item
:param default: return value if key is missing (default None)
:param bool read: ifTrue, return file handle to value
(default False)
:param float expire_time: ifTrue, return expire_time in tuple
(default False)
:param tag: ifTrue, return tag in tuple (default False)
:param bool retry: retry if database timeout occurs (default False)
:return: value for item if key is found else default
def read(self, key): """Return file handle corresponding to `key` from cache.
:param key: key for item
:return: file open for reading in binary mode
:raises KeyError: if key isnot found
"""
handle = self.get(key, default=ENOVAL, read=True, retry=True) if handle is ENOVAL: raise KeyError(key) return handle
def __contains__(self, key): """Return `True` if `key` matching item is found in cache.
:param key: key for item
:return: Trueif key is found
"""
index = self._hash(key) % self._count
shard = self._shards[index] return key in shard
def pop(
self, key, default=None, expire_time=False, tag=False, retry=False
): # noqa: E501 """Remove corresponding item for `key` from cache and return value.
If `key` is missing, return `default`.
Operation is atomic. Concurrent operations will be serialized.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param key: key for item
:param default: return value if key is missing (default None)
:param float expire_time: ifTrue, return expire_time in tuple
(default False)
:param tag: ifTrue, return tag in tuple (default False)
:param bool retry: retry if database timeout occurs (default False)
:return: value for item if key is found else default
def __delitem__(self, key): """Delete corresponding item for `key` from cache.
Calls :func:`FanoutCache.delete` internally with `retry` set to `True`.
:param key: key for item
:raises KeyError: if key isnot found
"""
index = self._hash(key) % self._count
shard = self._shards[index] del shard[key]
def check(self, fix=False, retry=False): """Check database and file system consistency.
Intended for use in testing and post-mortem error analysis.
While checking the cache table for consistency, a writer lock is held
on the database. The lock blocks other cache clients from writing to
the database. For caches with many file references, the lock may be
held for a long time. For example, local benchmarking shows that a
cache with 1,000 file references takes ~60ms to check.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param bool fix: correct inconsistencies
:param bool retry: retry if database timeout occurs (default False)
:return: list of warnings
:raises Timeout: if database timeout occurs
"""
warnings = (shard.check(fix, retry) for shard in self._shards) return functools.reduce(operator.iadd, warnings, [])
def expire(self, retry=False): """Remove expired items from cache.
If database timeout occurs then fails silently unless `retry` is set to
`True` (default `False`).
:param bool retry: retry if database timeout occurs (default False)
:return: count of items removed
"""
results = [shard.stats(enable, reset) for shard in self._shards]
total_hits = sum(hits for hits, _ in results)
total_misses = sum(misses for _, misses in results) return total_hits, total_misses
def volume(self): """Return estimated total size of cache on disk.
:return: size in bytes
""" return sum(shard.volume() for shard in self._shards)
def close(self): """Close database connection.""" for shard in self._shards:
shard.close()
self._caches.clear()
self._deques.clear()
self._indexes.clear()
def __iter__(self): """Iterate keys in cache including expired items."""
iterators = (iter(shard) for shard in self._shards) return it.chain.from_iterable(iterators)
def __reversed__(self): """Reverse iterate keys in cache including expired items."""
iterators = (reversed(shard) for shard in reversed(self._shards)) return it.chain.from_iterable(iterators)
def __len__(self): """Count of items in cache including expired items.""" return sum(len(shard) for shard in self._shards)
def reset(self, key, value=ENOVAL): """Reset `key` and `value` item from Settings table.
If `value` isnot given, it is reloaded from the Settings
table. Otherwise, the Settings table is updated.
Settings attributes on cache objects are lazy-loaded and
read-only. Use `reset` to update the value.
Settings with the ``sqlite_`` prefix correspond to SQLite
pragmas. Updating the value will execute the corresponding PRAGMA
statement.
:param str key: Settings key for item
:param value: value for item (optional)
:return: updated value for item
""" for shard in self._shards: whileTrue: try:
result = shard.reset(key, value) except Timeout: pass else: break return result
def cache(self, name, timeout=60, disk=None, **settings): """Return Cache with given `name` in subdirectory.
If disk isnone (default), uses the fanout cache disk.
:param str name: subdirectory name for Cache
:param float timeout: SQLite connection timeout
:param disk: Disk type or subclass for serialization
:param settings: any of DEFAULT_SETTINGS
:return: Cache with given name
"""
_caches = self._caches
try: return _caches[name] except KeyError:
parts = name.split('/')
directory = op.join(self._directory, 'cache', *parts)
temp = Cache(
directory=directory,
timeout=timeout,
disk=self._disk if disk isNoneelse Disk,
**settings,
)
_caches[name] = temp return temp
def deque(self, name, maxlen=None): """Return Deque with given `name` in subdirectory.
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.