desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'A version of update that uses our ``__setitem__``.'
| def update(self, indict):
| for entry in indict:
self[entry] = indict[entry]
|
'\'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised\''
| def pop(self, key, *args):
| val = dict.pop(self, key, *args)
if (key in self.scalars):
del self.comments[key]
del self.inline_comments[key]
self.scalars.remove(key)
elif (key in self.sections):
del self.comments[key]
del self.inline_comments[key]
self.sections.remove(key)
if (self.ma... |
'Pops the first (key,val)'
| def popitem(self):
| sequence = (self.scalars + self.sections)
if (not sequence):
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
return (key, val)
|
'A version of clear that also affects scalars/sections
Also clears comments and configspec.
Leaves other attributes alone :
depth/main/parent are not affected'
| def clear(self):
| dict.clear(self)
self.scalars = []
self.sections = []
self.comments = {}
self.inline_comments = {}
self.configspec = None
|
'A version of setdefault that sets sequence if appropriate.'
| def setdefault(self, key, default=None):
| try:
return self[key]
except KeyError:
self[key] = default
return self[key]
|
'D.items() -> list of D\'s (key, value) pairs, as 2-tuples'
| def items(self):
| return zip((self.scalars + self.sections), self.values())
|
'D.keys() -> list of D\'s keys'
| def keys(self):
| return (self.scalars + self.sections)
|
'D.values() -> list of D\'s values'
| def values(self):
| return [self[key] for key in (self.scalars + self.sections)]
|
'D.iteritems() -> an iterator over the (key, value) items of D'
| def iteritems(self):
| return iter(self.items())
|
'D.iterkeys() -> an iterator over the keys of D'
| def iterkeys(self):
| return iter((self.scalars + self.sections))
|
'D.itervalues() -> an iterator over the values of D'
| def itervalues(self):
| return iter(self.values())
|
'x.__repr__() <==> repr(x)'
| def __repr__(self):
| return ('{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key]))) for key in (self.scalars + self.sections)]))
|
'Return a deepcopy of self as a dictionary.
All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0'
| def dict(self):
| newdict = {}
for entry in self:
this_entry = self[entry]
if isinstance(this_entry, Section):
this_entry = this_entry.dict()
elif isinstance(this_entry, list):
this_entry = list(this_entry)
elif isinstance(this_entry, tuple):
this_entry = tuple(... |
'A recursive update - useful for merging config files.
>>> a = \'\'\'[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file\'\'\'.splitlines()
>>> b = \'\'\'# File is user.ini
... [section1]
... option1 = False
... # end of file\'\'\'.splitlines()
>>> c1 ... | def merge(self, indict):
| for (key, val) in indict.items():
if ((key in self) and isinstance(self[key], dict) and isinstance(val, dict)):
self[key].merge(val)
else:
self[key] = val
|
'Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.'
| def rename(self, oldkey, newkey):
| if (oldkey in self.scalars):
the_list = self.scalars
elif (oldkey in self.sections):
the_list = self.sections
else:
raise KeyError(('Key "%s" not found.' % oldkey))
pos = the_list.index(oldkey)
val = self[oldkey]
dict.__delitem__(self, oldkey)
dict.__setitem_... |
'Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror
unless ``raise_errors=False``, in which case set the return value to
``False``.
Any unrecognised keyword arguments you pass to walk, will be pased on
to the fun... | def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs):
| out = {}
for i in range(len(self.scalars)):
entry = self.scalars[i]
try:
val = function(self, entry, **keywargs)
entry = self.scalars[i]
out[entry] = val
except Exception:
if raise_errors:
raise
else:
... |
'Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` ... | def as_bool(self, key):
| val = self[key]
if (val == True):
return True
elif (val == False):
return False
else:
try:
if (not isinstance(val, basestring)):
raise KeyError()
else:
return self.main._bools[val.lower()]
except KeyError:
... |
'A convenience method which coerces the specified value to an integer.
If the value is an invalid literal for ``int``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a[\'a\'] = \'fish\'
>>> a.as_int(\'a\')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: \'fish\'
>>> a[\'... | def as_int(self, key):
| return int(self[key])
|
'A convenience method which coerces the specified value to a float.
If the value is an invalid literal for ``float``, a ``ValueError`` will
be raised.
>>> a = ConfigObj()
>>> a[\'a\'] = \'fish\'
>>> a.as_float(\'a\')
Traceback (most recent call last):
ValueError: invalid literal for float(): fish
>>> a[\'b\'] = \'1\'
>... | def as_float(self, key):
| return float(self[key])
|
'A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a[\'a\'] = 1
>>> a.as_list(\'a\')
[1]
>>> a[\'a\'] = (1,)
>>> a.as_list(\'a\')
[1]
>>> a[\'a\'] = [1]
>>> a.as_list(\'a\')
[1]'
| def as_list(self, key):
| result = self[key]
if isinstance(result, (tuple, list)):
return list(result)
return [result]
|
'Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
If there is no default value for this key, ``KeyError`` is raised.'
| def restore_default(self, key):
| default = self.default_values[key]
dict.__setitem__(self, key, default)
if (key not in self.defaults):
self.defaults.append(key)
return default
|
'Recursively restore default values to all members
that have them.
This method will only work for a ConfigObj that was created
with a configspec and has been validated.
It doesn\'t delete or modify entries without default values.'
| def restore_defaults(self):
| for key in self.default_values:
self.restore_default(key)
for section in self.sections:
self[section].restore_defaults()
|
'Parse a config file or create a config file object.
``ConfigObj(infile=None, options=None, **kwargs)``'
| def __init__(self, infile=None, options=None, _inspec=False, **kwargs):
| self._inspec = _inspec
Section.__init__(self, self, 0, self)
infile = (infile or [])
options = dict((options or {}))
options.update(kwargs)
if _inspec:
options['list_values'] = False
defaults = OPTION_DEFAULTS.copy()
for entry in options:
if (entry not in defaults):
... |
'Handle any BOM, and decode if necessary.
If an encoding is specified, that *must* be used - but the BOM should
still be removed (and the BOM attribute set).
(If the encoding is wrongly specified, then a BOM for an alternative
encoding won\'t be discovered or removed.)
If an encoding is not specified, UTF8 or UTF16 BOM... | def _handle_bom(self, infile):
| if ((self.encoding is not None) and (self.encoding.lower() not in BOM_LIST)):
return self._decode(infile, self.encoding)
if isinstance(infile, (list, tuple)):
line = infile[0]
else:
line = infile
if (self.encoding is not None):
enc = BOM_LIST[self.encoding.lower()]
... |
'Decode ASCII strings to unicode if a self.encoding is specified.'
| def _a_to_u(self, aString):
| if self.encoding:
return aString.decode('ascii')
else:
return aString
|
'Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.'
| def _decode(self, infile, encoding):
| if isinstance(infile, basestring):
return infile.decode(encoding).splitlines(True)
for (i, line) in enumerate(infile):
if (not isinstance(line, unicode)):
infile[i] = line.decode(encoding)
return infile
|
'Decode element to unicode if necessary.'
| def _decode_element(self, line):
| if (not self.encoding):
return line
if (isinstance(line, str) and self.default_encoding):
return line.decode(self.default_encoding)
return line
|
'Used by ``stringify`` within validate, to turn non-string values
into strings.'
| def _str(self, value):
| if (not isinstance(value, basestring)):
return str(value)
else:
return value
|
'Actually parse the config file.'
| def _parse(self, infile):
| temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = (len(infile) - 1)
cur_index = (-1)
reset_comment = False
while (cur_index < maxline):
if reset_comment:
comment_... |
'Given a section and a depth level, walk back through the sections
parents to see if the depth level matches a previous section.
Return a reference to the right section,
or raise a SyntaxError.'
| def _match_depth(self, sect, depth):
| while (depth < sect.depth):
if (sect is sect.parent):
raise SyntaxError()
sect = sect.parent
if (sect.depth == depth):
return sect
raise SyntaxError()
|
'Handle an error according to the error settings.
Either raise the error or store it.
The error will have occured at ``cur_index``'
| def _handle_error(self, text, ErrorClass, infile, cur_index):
| line = infile[cur_index]
cur_index += 1
message = (text % cur_index)
error = ErrorClass(message, cur_index, line)
if self.raise_errors:
raise error
self._errors.append(error)
|
'Return an unquoted version of a value'
| def _unquote(self, value):
| if ((value[0] == value[(-1)]) and (value[0] in ('"', "'"))):
value = value[1:(-1)]
return value
|
'Return a safely quoted version of a value.
Raise a ConfigObjError if the value cannot be safely quoted.
If multiline is ``True`` (default) then use triple quotes
if necessary.
* Don\'t quote values that don\'t need it.
* Recursively quote members of a list and return a comma joined list.
* Multiline is ``False`` for l... | def _quote(self, value, multiline=True):
| if (multiline and self.write_empty_values and (value == '')):
return ''
if (multiline and isinstance(value, (list, tuple))):
if (not value):
return ','
elif (len(value) == 1):
return (self._quote(value[0], multiline=False) + ',')
return ', '.join([self.... |
'Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)'
| def _handle_value(self, value):
| if self._inspec:
return (value, '')
if (not self.list_values):
mat = self._nolistvalue.match(value)
if (mat is None):
raise SyntaxError()
return mat.groups()
mat = self._valueexp.match(value)
if (mat is None):
raise SyntaxError()
(list_values, sing... |
'Extract the value, where we are in a multiline situation.'
| def _multiline(self, value, infile, cur_index, maxline):
| quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)
if (mat is not None):
retval = list(mat.groups())
retval.append(cur_index)
return retval
elif (newvalue.find(quot) !... |
'Parse the configspec.'
| def _handle_configspec(self, configspec):
| if (not isinstance(configspec, ConfigObj)):
try:
configspec = ConfigObj(configspec, raise_errors=True, file_error=True, _inspec=True)
except ConfigObjError as e:
raise ConfigspecError(('Parsing configspec failed: %s' % e))
except IOError as e:
rai... |
'Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__'
| def _set_configspec(self, section, copy):
| configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
for entry in section.sections:
if (entry not in configspec):
section[entry].configspec = many
for entry in configspec.sections:
if (entry == '__many__'):
c... |
'Write an individual line, for the write method'
| def _write_line(self, indent_string, entry, this_entry, comment):
| if (not self.unrepr):
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return ('%s%s%s%s%s' % (indent_string, self._decode_element(self._quote(entry, multiline=False)), self._a_to_u(' = '), val, self._decode_element(comment)))
|
'Write a section marker line'
| def _write_marker(self, indent_string, depth, entry, comment):
| return ('%s%s%s%s%s' % (indent_string, self._a_to_u(('[' * depth)), self._quote(self._decode_element(entry), multiline=False), self._a_to_u((']' * depth)), self._decode_element(comment)))
|
'Deal with a comment.'
| def _handle_comment(self, comment):
| if (not comment):
return ''
start = self.indent_type
if (not comment.startswith('#')):
start += self._a_to_u(' # ')
return (start + comment)
|
'Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = \'test.ini\'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj(\'test.ini\', raise_errors=True)
1'
| def write(self, outfile=None, section=None):
| if (self.indent_type is None):
self.indent_type = DEFAULT_INDENT_TYPE
out = []
cs = self._a_to_u('#')
csp = self._a_to_u('# ')
if (section is None):
int_val = self.interpolation
self.interpolation = False
section = self
for line in self.initial_comment:
... |
'Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj
was created - you can dynamically assign a dictionary of checks ... | def validate(self, validator, preserve_errors=False, copy=False, section=None):
| if (section is None):
if (self.configspec is None):
raise ValueError('No configspec supplied.')
if preserve_errors:
from validate import VdtMissingValue
self._vdtMissingValue = VdtMissingValue
section = self
if copy:
section.initi... |
'Clear ConfigObj instance and restore to \'freshly created\' state.'
| def reset(self):
| self.clear()
self._initialise()
self.configspec = None
self._original_configspec = None
|
'Reload a ConfigObj from file.
This method raises a ``ReloadError`` if the ConfigObj doesn\'t have
a filename attribute pointing to a file.'
| def reload(self):
| if (not isinstance(self.filename, basestring)):
raise ReloadError()
filename = self.filename
current_options = {}
for entry in OPTION_DEFAULTS:
if (entry == 'configspec'):
continue
current_options[entry] = getattr(self, entry)
configspec = self._original_configspe... |
'A dummy check method, always returns the value unchanged.'
| def check(self, check, member, missing=False):
| if missing:
raise self.baseErrorClass()
return member
|
'Acquire the \'read\' lock.'
| def acquire_read_lock(self, wait=True):
| self.condition.acquire()
try:
if wait:
while (self.current_sync_operation is not None):
self.condition.wait()
elif (self.current_sync_operation is not None):
return False
self.async += 1
log.debug('%s acquired read lock', self)
... |
'Release the \'read\' lock.'
| def release_read_lock(self):
| self.condition.acquire()
try:
self.async -= 1
if (self.async == 0):
if (self.current_sync_operation is not None):
self.condition.notifyAll()
elif (self.async < 0):
raise LockError('Synchronizer error - too many release_read_locks ... |
'Acquire the \'write\' lock.'
| def acquire_write_lock(self, wait=True):
| self.condition.acquire()
try:
if wait:
while (self.current_sync_operation is not None):
self.condition.wait()
elif (self.current_sync_operation is not None):
return False
self.current_sync_operation = threading.currentThread()
if (self.asyn... |
'Release the \'write\' lock.'
| def release_write_lock(self):
| self.condition.acquire()
try:
if (self.current_sync_operation is not threading.currentThread()):
raise LockError("Synchronizer error - current thread doesn't have the write lock")
self.current_sync_operation = None
self.condition.notifyAll()
... |
'Create a new :class:`.NameRegistry`.'
| def __init__(self, creator):
| self._values = weakref.WeakValueDictionary()
self._mutex = threading.RLock()
self.creator = creator
|
'Get and possibly create the value.
:param identifier: Hash key for the value.
If the creation function is called, this identifier
will also be passed to the creation function.
:param \*args, \**kw: Additional arguments which will
also be passed to the creation function if it is
called.'
| def get(self, identifier, *args, **kw):
| try:
if (identifier in self._values):
return self._values[identifier]
else:
return self._sync_get(identifier, *args, **kw)
except KeyError:
return self._sync_get(identifier, *args, **kw)
|
'Construct a new :class:`.Dogpile`.'
| def __init__(self, expiretime, init=False, lock=None):
| if lock:
self.dogpilelock = lock
else:
self.dogpilelock = threading.Lock()
self.expiretime = expiretime
if init:
self.createdtime = time.time()
|
'Acquire the lock, returning a context manager.
:param creator: Creation function, used if this thread
is chosen to create a new value.
:param value_fn: Optional function that returns
the value from some datasource. Will be returned
if regeneration is not needed.
:param value_and_created_fn: Like value_fn, but returns... | def acquire(self, creator, value_fn=None, value_and_created_fn=None):
| if (value_and_created_fn is None):
if (value_fn is None):
def value_and_created_fn():
return (None, self.createdtime)
else:
def value_and_created_fn():
return (value_fn(), self.createdtime)
def creator_wrapper():
value = cre... |
'Return true if the expiration time is reached, or no
value is available.'
| @property
def is_expired(self):
| return ((not self.has_value) or ((self.expiretime is not None) and ((time.time() - self.createdtime) > self.expiretime)))
|
'Return true if the creation function has proceeded
at least once.'
| @property
def has_value(self):
| return (self.createdtime > 0)
|
'Return the "write" lock context manager.
This will provide a section that is mutexed against
all readers/writers for the dogpile-maintained value.'
| @contextlib.contextmanager
def acquire_write_lock(self):
| self.readwritelock.acquire_write_lock()
try:
(yield)
finally:
self.readwritelock.release_write_lock()
|
'Return true if the expiration time is reached, or no
value is available.'
| def _is_expired(self, createdtime):
| return ((not self._has_value(createdtime)) or ((self.expiretime is not None) and ((time.time() - createdtime) > self.expiretime)))
|
'Return true if the creation function has proceeded
at least once.'
| def _has_value(self, createdtime):
| return (createdtime > 0)
|
'client library imports go here.'
| def _imports(self):
| raise NotImplementedError()
|
'Creation of a Client instance goes here.'
| def _create_client(self):
| raise NotImplementedError()
|
'Return the memcached client.
This uses a threading.local by
default as it appears most modern
memcached libs aren\'t inherently
threadsafe.'
| @property
def client(self):
| return self._clients.memcached
|
'python-binary-memcached api does not implements delete_multi'
| def delete_multi(self, keys):
| for key in keys:
self.delete(key)
|
'Constructor, is given the filename of a potential lockfile.
The usage of this filename is optional and no file is
created by default.
Raises ``NotImplementedError`` by default, must be
implemented by subclasses.'
| def __init__(self, filename):
| raise NotImplementedError()
|
'Acquire the "write" lock.
This is a direct call to :meth:`.AbstractFileLock.acquire_write_lock`.'
| def acquire(self, wait=True):
| return self.acquire_write_lock(wait)
|
'Release the "write" lock.
This is a direct call to :meth:`.AbstractFileLock.release_write_lock`.'
| def release(self):
| self.release_write_lock()
|
'Provide a context manager for the "read" lock.
This method makes use of :meth:`.AbstractFileLock.acquire_read_lock`
and :meth:`.AbstractFileLock.release_read_lock`'
| @contextmanager
def read(self):
| self.acquire_read_lock(True)
try:
(yield)
finally:
self.release_read_lock()
|
'Provide a context manager for the "write" lock.
This method makes use of :meth:`.AbstractFileLock.acquire_write_lock`
and :meth:`.AbstractFileLock.release_write_lock`'
| @contextmanager
def write(self):
| self.acquire_write_lock(True)
try:
(yield)
finally:
self.release_write_lock()
|
'optional method.'
| @property
def is_open(self):
| raise NotImplementedError()
|
'Acquire a \'reader\' lock.
Raises ``NotImplementedError`` by default, must be
implemented by subclasses.'
| def acquire_read_lock(self, wait):
| raise NotImplementedError()
|
'Acquire a \'write\' lock.
Raises ``NotImplementedError`` by default, must be
implemented by subclasses.'
| def acquire_write_lock(self, wait):
| raise NotImplementedError()
|
'Release a \'reader\' lock.
Raises ``NotImplementedError`` by default, must be
implemented by subclasses.'
| def release_read_lock(self):
| raise NotImplementedError()
|
'Release a \'writer\' lock.
Raises ``NotImplementedError`` by default, must be
implemented by subclasses.'
| def release_write_lock(self):
| raise NotImplementedError()
|
'Take a backend as an argument and setup the self.proxied property.
Return an object that be used as a backend by a :class:`.CacheRegion`
object.'
| def wrap(self, backend):
| assert (isinstance(backend, CacheBackend) or isinstance(backend, ProxyBackend))
self.proxied = backend
return self
|
'Construct a new :class:`.CacheRegion`.'
| def __init__(self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None):
| self.name = name
self.function_key_generator = function_key_generator
self.function_multi_key_generator = function_multi_key_generator
if key_mangler:
self.key_mangler = key_mangler
else:
self.key_mangler = None
self._hard_invalidated = None
self._soft_invalidated = 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... | def configure(self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None):
| if ('backend' in self.__dict__):
raise exception.RegionAlreadyConfigured(('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_argum... |
'Takes a ProxyBackend instance or class and wraps the
attached backend.'
| def wrap(self, proxy):
| if (type(proxy) == type):
proxy = proxy()
if (not issubclass(type(proxy), ProxyBackend)):
raise TypeError(('Type %s is not a valid ProxyBackend' % type(proxy)))
self.backend = proxy.wrap(self.backend)
|
'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... | def invalidate(self, hard=True):
| if hard:
self._hard_invalidated = time.time()
self._soft_invalidated = None
else:
self._hard_invalidated = None
self._soft_invalidated = time.time()
|
'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.arg... | def configure_from_config(self, config_dict, prefix):
| 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), wrap=config_dict.get(('%swrap' % prefix), None))
|
'Return True if the backend has been configured via the
:meth:`.CacheRegion.configure` method already.
.. versionadded:: 0.5.1'
| @property
def is_configured(self):
| return ('backend' in self.__dict__)
|
'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 al... | def get(self, key, expiration_time=None, ignore_expiration=False):
| 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
|
'Return multiple values from the cache, based on the given keys.
Returns values as a list matching the keys given.
E.g.::
values = region.get_multi(["one", "two", "three"])
To convert values to a dictionary, use ``zip()``::
keys = ["one", "two", "three"]
values = region.get_multi(keys)
dictionary = dict(zip(keys, value... | def get_multi(self, keys, expiration_time=None, ignore_expiration=False):
| if (not keys):
return []
if self.key_mangler:
keys = list(map((lambda key: self.key_mangler(key)), keys))
backend_values = self.backend.get_multi(keys)
_unexpired_value_fn = self._unexpired_value_fn(expiration_time, ignore_expiration)
return [(value.payload if (value is not NO_VALUE)... |
'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.
Whether or not the function is used depends on if the
*dogpil... | def get_or_create(self, key, creator, expiration_time=None, should_cache_fn=None):
| orig_key = key
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._hard_invalidated and (value.metadata['ct'] < self._hard_invalidated))):
raise NeedReg... |
'Return a sequence of cached values based on a sequence of keys.
The behavior for generation of values based on keys corresponds
to that of :meth:`.Region.get_or_create`, with the exception that
the ``creator()`` function may be asked to generate any subset of
the given keys. The list of keys to be generated is passe... | def get_or_create_multi(self, keys, creator, expiration_time=None, should_cache_fn=None):
| def get_value(key):
value = values.get(key, NO_VALUE)
if ((value is NO_VALUE) or (value.metadata['v'] != value_version) or (self._hard_invalidated and (value.metadata['ct'] < self._hard_invalidated))):
return (value.payload, 0)
else:
ct = value.metadata['ct']
... |
'Return a :class:`.CachedValue` given a value.'
| def _value(self, value):
| return CachedValue(value, {'ct': time.time(), 'v': value_version})
|
'Place a new value in the cache under the given key.'
| def set(self, key, value):
| if self.key_mangler:
key = self.key_mangler(key)
self.backend.set(key, self._value(value))
|
'Place new values in the cache under the given keys.
.. versionadded:: 0.5.0'
| def set_multi(self, mapping):
| if (not mapping):
return
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)
|
'Remove a value from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)'
| def delete(self, key):
| if self.key_mangler:
key = self.key_mangler(key)
self.backend.delete(key)
|
'Remove multiple values from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)
.. versionadded:: 0.5.0'
| def delete_multi(self, keys):
| if self.key_mangler:
keys = list(map((lambda key: self.key_mangler(key)), keys))
self.backend.delete_multi(keys)
|
'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 d... | def cache_on_arguments(self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None):
| expiration_time_is_callable = compat.callable(expiration_time)
if (function_key_generator is None):
function_key_generator = self.function_key_generator
def decorator(fn):
if (to_str is compat.string_type):
key_generator = function_key_generator(namespace, fn)
else:
... |
'A function decorator that will cache multiple return
values from the function using a sequence of keys derived from the
function itself and the arguments passed to it.
This method is the "multiple key" analogue to the
:meth:`.CacheRegion.cache_on_arguments` method.
Example::
@someregion.cache_multi_on_arguments()
def ... | def cache_multi_on_arguments(self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None):
| expiration_time_is_callable = compat.callable(expiration_time)
if (function_multi_key_generator is None):
function_multi_key_generator = self.function_multi_key_generator
def decorator(fn):
key_generator = function_multi_key_generator(namespace, fn, to_str=to_str)
@wraps(fn)
... |
'Construct a new :class:`.CacheBackend`.
Subclasses should override this to
handle the given arguments.
:param arguments: The ``arguments`` parameter
passed to :func:`.make_registry`.'
| def __init__(self, arguments):
| raise NotImplementedError()
|
'Return an optional mutexing object for the given key.
This object need only provide an ``acquire()``
and ``release()`` method.
May return ``None``, in which case the dogpile
lock will use a regular ``threading.Lock``
object to mutex concurrent threads for
value creation. The default implementation
returns ``None``.
... | def get_mutex(self, key):
| return None
|
'Retrieve a value from the cache.
The returned value should be an instance of
:class:`.CachedValue`, or ``NO_VALUE`` if
not present.'
| def get(self, key):
| raise NotImplementedError()
|
'Retrieve multiple values from the cache.
The returned value should be a list, corresponding
to the list of keys given.
.. versionadded:: 0.5.0'
| def get_multi(self, keys):
| raise NotImplementedError()
|
'Set a value in the cache.
The key will be whatever was passed
to the registry, processed by the
"key mangling" function, if any.
The value will always be an instance
of :class:`.CachedValue`.'
| def set(self, key, value):
| raise NotImplementedError()
|
'Set multiple values in the cache.
The key will be whatever was passed
to the registry, processed by the
"key mangling" function, if any.
The value will always be an instance
of :class:`.CachedValue`.
.. versionadded:: 0.5.0'
| def set_multi(self, mapping):
| raise NotImplementedError()
|
'Delete a value from the cache.
The key will be whatever was passed
to the registry, processed by the
"key mangling" function, if any.
The behavior here should be idempotent,
that is, can be called any number of times
regardless of whether or not the
key exists.'
| def delete(self, key):
| raise NotImplementedError()
|
'Delete multiple values from the cache.
The key will be whatever was passed
to the registry, processed by the
"key mangling" function, if any.
The behavior here should be idempotent,
that is, can be called any number of times
regardless of whether or not the
key exists.
.. versionadded:: 0.5.0'
| def delete_multi(self, keys):
| raise NotImplementedError()
|
'Helper for clearing all the keys in a database. Use with
caution!'
| def clear(self):
| for key in self.conn.keys():
self.conn.delete(key)
|
'Verify our vary headers match and construct a real urllib3
HTTPResponse object.'
| def prepare_response(self, request, cached):
| if ('*' in cached.get('vary', {})):
return
for (header, value) in cached.get('vary', {}).items():
if (request.headers.get(header, None) != value):
return
body_raw = cached['response'].pop('body')
try:
body = io.BytesIO(body_raw)
except TypeError:
body = io... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.