signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@classmethod<EOL><INDENT>def get_class_field(cls, field_name):<DEDENT> | if not cls.has_field(field_name):<EOL><INDENT>raise AttributeError('<STR_LIT>' %<EOL>(field_name, cls.__name__))<EOL><DEDENT>field = getattr(cls, '<STR_LIT>' % field_name)<EOL>return field<EOL> | Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form) | f15573:c1:m7 |
def get_instance_field(self, field_name): | if not self.has_field(field_name):<EOL><INDENT>raise AttributeError('<STR_LIT>' %<EOL>(field_name, self.__class__.__name__))<EOL><DEDENT>field = getattr(self, field_name)<EOL>return field<EOL> | Return the field object with the given name (works for a bound instance) | f15573:c1:m8 |
def _set_pk(self, value): | if self._pk:<EOL><INDENT>raise ImplementationError('<STR_LIT>')<EOL><DEDENT>self._pk = value<EOL>self._connected = True<EOL>self._set_defaults()<EOL> | Use the given value as the instance's primary key, if it doesn't have
one yet (it must be used only for new instances). Then save default values. | f15573:c1:m9 |
def _set_defaults(self): | for field_name in self._fields:<EOL><INDENT>if field_name in self._init_fields:<EOL><INDENT>continue<EOL><DEDENT>field = self.get_field(field_name)<EOL>if hasattr(field, "<STR_LIT:default>"):<EOL><INDENT>field.proxy_set(field.default)<EOL><DEDENT><DEDENT> | Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk. | f15573:c1:m10 |
@classmethod<EOL><INDENT>def _field_is_pk(cls, name):<DEDENT> | return name in ('<STR_LIT>', cls.get_field('<STR_LIT>').name)<EOL> | Check if the given field is the one from the primary key.
It can be the plain "pk" name, or the real pk field name | f15573:c1:m13 |
@classmethod<EOL><INDENT>def exists(cls, **kwargs):<DEDENT> | if not kwargs:<EOL><INDENT>raise ValueError(u"<STR_LIT>")<EOL><DEDENT>if len(kwargs) == <NUM_LIT:1> and cls._field_is_pk(list(kwargs.keys())[<NUM_LIT:0>]):<EOL><INDENT>return cls.get_field('<STR_LIT>').exists(list(kwargs.values())[<NUM_LIT:0>])<EOL><DEDENT>try:<EOL><INDENT>cls.collection(**kwargs).sort(by='<STR_LIT>')[... | A model with the values defined by kwargs exists in db?
`kwargs` are mandatory. | f15573:c1:m14 |
@classmethod<EOL><INDENT>def get(cls, *args, **kwargs):<DEDENT> | if len(args) == <NUM_LIT:1>: <EOL><INDENT>pk = args[<NUM_LIT:0>]<EOL><DEDENT>elif kwargs:<EOL><INDENT>if len(kwargs) == <NUM_LIT:1> and cls._field_is_pk(list(kwargs.keys())[<NUM_LIT:0>]):<EOL><INDENT>pk = list(kwargs.values())[<NUM_LIT:0>]<EOL><DEDENT>else: <EOL><INDENT>result = cls.collection(**kwargs).sort(by='<STR... | Retrieve one instance from db according to given kwargs.
Optionnaly, one arg could be used to retrieve it from pk. | f15573:c1:m15 |
@classmethod<EOL><INDENT>def get_or_connect(cls, **kwargs):<DEDENT> | try:<EOL><INDENT>inst = cls.get(**kwargs)<EOL>created = False<EOL><DEDENT>except DoesNotExist:<EOL><INDENT>inst = cls(**kwargs)<EOL>created = True<EOL><DEDENT>except Exception:<EOL><INDENT>raise<EOL><DEDENT>return inst, created<EOL> | Try to retrieve an object in db, and create it if it does not exist. | f15573:c1:m16 |
@classmethod<EOL><INDENT>def sort_wildcard(cls):<DEDENT> | return cls.make_key(<EOL>cls._name,<EOL>"<STR_LIT:*>",<EOL>"<STR_LIT>",<EOL>)<EOL> | Used to sort Hashfield. See Hashfield.sort_widlcard. | f15573:c1:m19 |
def hmget(self, *args): | if args and not any(arg in self._instancehash_fields for arg in args):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return self._call_command('<STR_LIT>', args)<EOL> | This command on the model allow getting many instancehash fields with only
one redis call. You must pass hash name to retrieve as arguments. | f15573:c1:m20 |
def hmset(self, **kwargs): | if kwargs and not any(kwarg in self._instancehash_fields for kwarg in iterkeys(kwargs)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>indexed = []<EOL>try:<EOL><INDENT>for field_name, value in iteritems(kwargs):<EOL><INDENT>field = self.get_field(field_name)<EOL>if field.indexable:<EOL><INDENT>indexed.append(f... | This command on the model allow setting many instancehash fields with only
one redis call. You must pass kwargs with field names as keys, with
their value. | f15573:c1:m21 |
def hdel(self, *args): | if args and not any(arg in self._instancehash_fields for arg in args):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for field_name in args:<EOL><INDENT>field = self.get_field(field_name)<EOL>if field.indexable:<EOL><INDENT>field.deindex()<EOL><DEDENT><DEDENT>return self._call_command('<STR_LIT>', *args)<EOL> | This command on the model allow deleting many instancehash fields with
only one redis call. You must pass hash names to retrieve as arguments | f15573:c1:m22 |
def delete(self): | <EOL>for field_name in self._fields:<EOL><INDENT>field = self.get_field(field_name)<EOL>if not isinstance(field, PKField):<EOL><INDENT>field.delete()<EOL><DEDENT><DEDENT>self.connection.srem(self.get_field('<STR_LIT>').collection_key, self._pk)<EOL>delattr(self, "<STR_LIT>")<EOL> | Delete the instance from redis storage. | f15573:c1:m23 |
@classmethod<EOL><INDENT>def _thread_lock_storage(cls):<DEDENT> | if not hasattr(threadlocal, '<STR_LIT>'):<EOL><INDENT>threadlocal.limpyd_locked_fields = {}<EOL><DEDENT>if cls._name not in threadlocal.limpyd_locked_fields:<EOL><INDENT>threadlocal.limpyd_locked_fields[cls._name] = set()<EOL><DEDENT>return threadlocal.limpyd_locked_fields[cls._name]<EOL> | We mark each locked field in a thread, to allow other operations in the
same thread on the same field (for the same instance or others). This
way, operations within the lock, in the same thread, can bypass it (the
whole set of operations must be locked) | f15573:c1:m24 |
def scan_keys(self, count=None): | pattern = self.make_key(<EOL>self._name,<EOL>self.pk.get(),<EOL>'<STR_LIT:*>'<EOL>)<EOL>return self.database.scan_keys(pattern, count)<EOL> | Iter on all the key related to the current instance fields, using redis SCAN command
Parameters
----------
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
-------
str
All keys found by the sca... | f15573:c1:m28 |
@classmethod<EOL><INDENT>def scan_model_keys(cls, count=None):<DEDENT> | pattern = cls.make_key(<EOL>cls._name,<EOL>"<STR_LIT:*>",<EOL>)<EOL>return cls.database.scan_keys(pattern, count)<EOL> | Iter on all the key related to the current model, using redis SCAN command
Parameters
----------
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
-------
str
All keys found by the scan, one by ... | f15573:c1:m29 |
def __init__(self, field): | self.field = field<EOL>self._reset_cache()<EOL> | Attach the index to the given field and prepare the internal cache | f15574:c0:m0 |
@classmethod<EOL><INDENT>def configure(cls, **kwargs):<DEDENT> | attrs = {}<EOL>for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:key>'):<EOL><INDENT>if key in kwargs:<EOL><INDENT>attrs[key] = kwargs.pop(key)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>attrs['<STR_LIT>'] = staticmethod(kwargs.pop('<STR_LIT>'))<EOL><DEDENT>name = kwargs.pop('<STR_LIT:name>', None)<EOL>if ... | Create a new index class with the given info
This allow to avoid creating a new class when only few changes are
to be made
Parameters
----------
kwargs: dict
prefix: str
The string part to use in the collection, before the normal suffix.
... | f15574:c0:m1 |
def can_handle_suffix(self, suffix): | try:<EOL><INDENT>return self.remove_prefix(suffix) in self.handled_suffixes<EOL><DEDENT>except IndexError:<EOL><INDENT>return False<EOL><DEDENT> | Tell if the current index can be used for the given filter suffix
Parameters
----------
suffix: str
The filter suffix we want to check. Must not includes the "__" part.
Returns
-------
bool
``True`` if the index can handle this suffix, ``False`` ... | f15574:c0:m2 |
def normalize_value(self, value, transform=True): | if transform:<EOL><INDENT>value = self.transform_value(value)<EOL><DEDENT>return str(self.field.from_python(value))<EOL> | Prepare the given value to be stored in the index
It first calls ``transform_value`` if ``transform`` is ``True``, then
calls the ``from_python`` method of the field, then cast the result
to a str.
Parameters
----------
value: any
The value to normalize
... | f15574:c0:m3 |
def transform_value(self, value): | if not self.transform:<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>return self.transform(self, value)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>if '<STR_LIT>' in str(e): <EOL><INDENT>return self.transform(value)<EOL><DEDENT><DEDENT> | Convert the value to be stored.
This does nothing by default but subclasses can change this.
Then the index will be able to filter on the transformed value.
For example if the transform capitalizes some text, the filter
would be ``myfield__capitalized__eq='FOO'`` | f15574:c0:m4 |
@classmethod<EOL><INDENT>def remove_prefix(cls, suffix):<DEDENT> | if not cls.prefix:<EOL><INDENT>return suffix<EOL><DEDENT>if cls.prefix == suffix:<EOL><INDENT>return None<EOL><DEDENT>return (suffix or '<STR_LIT>').split(cls.prefix + '<STR_LIT>')[<NUM_LIT:1>] or None<EOL> | Remove the class prefix from the suffix
The collection pass the full suffix used in the filters to the index.
But to know if it is valid, we have to remove the prefix to get the
real suffix, for example to check if the suffix is handled by the index.
Parameters
-----------
... | f15574:c0:m5 |
@property<EOL><INDENT>def connection(self):<DEDENT> | return self.field.connection<EOL> | Shortcut to get the redis connection of the field tied to this index | f15574:c0:m6 |
@property<EOL><INDENT>def model(self):<DEDENT> | return self.field._model<EOL> | Shortcut to get the model tied to the field tied to this index | f15574:c0:m7 |
@property<EOL><INDENT>def attached_to_model(self):<DEDENT> | try:<EOL><INDENT>if not bool(self.model):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return not bool(self.instance)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return True<EOL><DEDENT><DEDENT> | Tells if the current index is the one attached to the model field, not instance field | f15574:c0:m8 |
@property<EOL><INDENT>def instance(self):<DEDENT> | return self.field._instance<EOL> | Shortcut to get the instance tied to the field tied to this index | f15574:c0:m9 |
def _reset_cache(self): | self._indexed_values = set()<EOL>self._deindexed_values = set()<EOL> | Reset attributes used to potentially rollback the indexes | f15574:c0:m10 |
def _rollback(self): | <EOL>indexed_values = set(self._indexed_values)<EOL>deindexed_values = set(self._deindexed_values)<EOL>for args in indexed_values:<EOL><INDENT>self.remove(*args)<EOL><DEDENT>for args in deindexed_values:<EOL><INDENT>self.add(*args, check_uniqueness=False)<EOL><DEDENT> | Restore the index in its previous state
This uses values that were indexed/deindexed since the last call
to `_reset_cache`.
This is used when an error is encountered while updating a value,
to return to the previous state | f15574:c0:m11 |
def get_filtered_keys(self, suffix, *args, **kwargs): | raise NotImplementedError<EOL> | Returns the index keys to be used by the collection for the given args
Parameters
-----------
suffix: str
The suffix used in the filter that called this index
Useful if the index supports many suffixes doing different things
args: tuple
All the "val... | f15574:c0:m12 |
def check_uniqueness(self, *args): | raise NotImplementedError<EOL> | For a unique index, check if the given args are not used twice
To implement this method in subclasses, get pks for the value (via `args`)
then call ``assert_pks_uniqueness`` (see in ``EqualIndex``)
Parameters
----------
args: tuple
All the values to take into accoun... | f15574:c0:m13 |
def assert_pks_uniqueness(self, pks, exclude, value): | pks = list(set(pks))<EOL>if len(pks) > <NUM_LIT:1>:<EOL><INDENT>raise UniquenessError(<EOL>"<STR_LIT>" % (<EOL>self.model.__name__, self.field.name, pks<EOL>)<EOL>)<EOL><DEDENT>elif len(pks) == <NUM_LIT:1> and (not exclude or pks[<NUM_LIT:0>] != exclude):<EOL><INDENT>self.connection.delete(self.field.key)<EOL>raise Uni... | Check uniqueness of pks
Parameters
-----------
pks: iterable
The pks to check for uniqueness. If more than one different,
it will raise. If only one and different than `exclude`, it will
raise too.
exclude: str
The pk that we accept to be ... | f15574:c0:m14 |
def add(self, *args, **kwargs): | raise NotImplementedError<EOL> | Add the instance tied to the field for the given "value" (via `args`) to the index
Parameters
----------
args: tuple
All the values to take into account to define the index entry
kwargs: dict
check_uniqueness: bool
When ``True`` (the default), if ... | f15574:c0:m15 |
def remove(self, *args): | raise NotImplementedError<EOL> | Remove the instance tied to the field for the given "value" (via `args`) from the index
Parameters
----------
args: tuple
All the values to take into account to define the index entry | f15574:c0:m16 |
def get_all_storage_keys(self): | raise NotImplementedError<EOL> | Returns the keys to be removed by `clear` in aggressive mode
Returns
-------
set
The set of all keys that matches the keys used by this index. | f15574:c0:m17 |
def clear(self, chunk_size=<NUM_LIT:1000>, aggressive=False): | assert self.attached_to_model,'<STR_LIT>'<EOL>if aggressive:<EOL><INDENT>keys = self.get_all_storage_keys()<EOL>with self.model.database.pipeline(transaction=False) as pipe:<EOL><INDENT>for key in keys:<EOL><INDENT>pipe.delete(key)<EOL><DEDENT>pipe.execute()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>start = <NUM_LIT:0><EOL... | Will deindex all the value for the current field
Parameters
----------
chunk_size: int
Default to 1000, it's the number of instances to load at once if not in aggressive mode.
aggressive: bool
Default to ``False``. When ``False``, the actual collection of instanc... | f15574:c0:m18 |
def rebuild(self, chunk_size=<NUM_LIT:1000>, aggressive_clear=False): | assert self.attached_to_model,'<STR_LIT>'<EOL>self.clear(chunk_size=chunk_size, aggressive=aggressive_clear)<EOL>start = <NUM_LIT:0><EOL>while True:<EOL><INDENT>instances = self.model.collection().sort().instances(skip_exist_test=True)[start:start + chunk_size]<EOL>for instance in instances:<EOL><INDENT>field = instanc... | Rebuild the whole index for this field.
Parameters
----------
chunk_size: int
Default to 1000, it's the number of instances to load at once.
aggressive_clear: bool
Will be passed to the `aggressive` argument of the `clear` method.
If `False`, all valu... | f15574:c0:m19 |
def get_filtered_keys(self, suffix, *args, **kwargs): | accepted_key_types = kwargs.get('<STR_LIT>', None)<EOL>if accepted_key_types and '<STR_LIT>' not in accepted_key_types:<EOL><INDENT>raise ImplementationError(<EOL>'<STR_LIT>' % self.__class__.__name__<EOL>)<EOL><DEDENT>if suffix == '<STR_LIT>':<EOL><INDENT>args = list(args)<EOL>values = set(args.pop())<EOL>if not value... | Return the set used by the index for the given "value" (`args`)
For the parameters, see ``BaseIndex.get_filtered_keys`` | f15574:c1:m0 |
def get_storage_key(self, *args, **kwargs): | args = list(args)<EOL>value = args.pop()<EOL>parts = [<EOL>self.model._name,<EOL>self.field.name,<EOL>] + args<EOL>if self.prefix:<EOL><INDENT>parts.append(self.prefix)<EOL><DEDENT>if self.key:<EOL><INDENT>parts.append(self.key)<EOL><DEDENT>normalized_value = self.normalize_value(value, transform=kwargs.get('<STR_LIT>'... | Return the redis key where to store the index for the given "value" (`args`)
For this index, we store all PKs having the same value for a field in the same
set. Key has this form:
model-name:field-name:sub-field-name:normalized-value
The ':sub-field-name part' is repeated for each entry... | f15574:c1:m1 |
def get_all_storage_keys(self): | parts1 = [<EOL>self.model._name,<EOL>self.field.name,<EOL>]<EOL>parts2 = parts1 + ['<STR_LIT:*>'] <EOL>if self.prefix:<EOL><INDENT>parts1.append(self.prefix)<EOL>parts2.append(self.prefix)<EOL><DEDENT>if self.key:<EOL><INDENT>parts1.append(self.key)<EOL>parts2.append(self.key)<EOL><DEDENT>parts1.append('<STR_LIT:*>')<... | Returns the keys to be removed by `clear` in aggressive mode
For the parameters, see BaseIndex.get_all_storage_keys | f15574:c1:m2 |
def check_uniqueness(self, *args, **kwargs): | if not self.field.unique:<EOL><INDENT>return<EOL><DEDENT>key = kwargs.get('<STR_LIT:key>', None)<EOL>if key is None:<EOL><INDENT>key = self.get_storage_key(*args)<EOL><DEDENT>pk = self.instance.pk.get()<EOL>pks = list(self.connection.smembers(key))<EOL>self.assert_pks_uniqueness(pks, pk, list(args)[-<NUM_LIT:1>])<EOL> | Check if the given "value" (via `args`) is unique or not.
Parameters
----------
kwargs: dict
key: str
When given, it will be used instead of calling ``get_storage_key``
for the given args
MUST be passed as a keyword argument
F... | f15574:c1:m3 |
def add(self, *args, **kwargs): | check_uniqueness = kwargs.get('<STR_LIT>', True)<EOL>key = self.get_storage_key(*args)<EOL>if self.field.unique and check_uniqueness:<EOL><INDENT>self.check_uniqueness(key=key, *args)<EOL><DEDENT>pk = self.instance.pk.get()<EOL>logger.debug("<STR_LIT>" % (pk, key))<EOL>self.connection.sadd(key, pk)<EOL>self._indexed_va... | Add the instance tied to the field for the given "value" (via `args`) to the index
For the parameters, see ``BaseIndex.add`` | f15574:c1:m4 |
def remove(self, *args): | key = self.get_storage_key(*args)<EOL>pk = self.instance.pk.get()<EOL>logger.debug("<STR_LIT>" % (pk, key))<EOL>self.connection.srem(key, pk)<EOL>self._deindexed_values.add(tuple(args))<EOL> | Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove`` | f15574:c1:m5 |
def get_storage_key(self, *args): | args = list(args)<EOL>args.pop() <EOL>parts = [<EOL>self.model._name,<EOL>self.field.name,<EOL>] + args<EOL>if self.prefix:<EOL><INDENT>parts.append(self.prefix)<EOL><DEDENT>if self.key:<EOL><INDENT>parts.append(self.key)<EOL><DEDENT>return self.field.make_key(*parts)<EOL> | Return the redis key where to store the index for the given "value" (`args`)
For this index, we store all PKs having for a field in the same sorted-set.
Key has this form:
model-name:field-name:sub-field-name:index-key-name
The ':sub-field-name part' is repeated for each entry in *args ... | f15574:c2:m0 |
def get_all_storage_keys(self): | parts1 = [<EOL>self.model._name,<EOL>self.field.name,<EOL>]<EOL>parts2 = parts1 + ['<STR_LIT:*>'] <EOL>if self.prefix:<EOL><INDENT>parts1.append(self.prefix)<EOL>parts2.append(self.prefix)<EOL><DEDENT>if self.key:<EOL><INDENT>parts1.append(self.key)<EOL>parts2.append(self.key)<EOL><DEDENT>return set(<EOL>self.model.da... | Returns the keys to be removed by `clear` in aggressive mode
For the parameters, see BaseIndex.get_all_storage_keys | f15574:c2:m1 |
def prepare_value_for_storage(self, value, pk): | return self.normalize_value(value)<EOL> | Prepare the value to be stored in the zset
Parameters
----------
value: any
The value, to normalize, to use
pk: any
The pk, that will be stringified
Returns
-------
str
The string ready to use as member of the sorted set. | f15574:c2:m2 |
def check_uniqueness(self, *args, **kwargs): | if not self.field.unique:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>pk = self.instance.pk.get()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pk = None<EOL><DEDENT>key = self.get_storage_key(*args)<EOL>value = list(args)[-<NUM_LIT:1>]<EOL>pks = self.get_pks_for_filter(key, '<STR_LIT>', self.normalize_value(value... | Check if the given "value" (via `args`) is unique or not.
For the parameters, see ``BaseIndex.check_uniqueness`` | f15574:c2:m3 |
def add(self, *args, **kwargs): | check_uniqueness = kwargs.get('<STR_LIT>', True)<EOL>if self.field.unique and check_uniqueness:<EOL><INDENT>self.check_uniqueness(*args)<EOL><DEDENT>key = self.get_storage_key(*args)<EOL>args = list(args)<EOL>value = args[-<NUM_LIT:1>]<EOL>pk = self.instance.pk.get()<EOL>logger.debug("<STR_LIT>" % (pk, key))<EOL>self.s... | Add the instance tied to the field for the given "value" (via `args`) to the index
For the parameters, see ``BaseIndex.add``
Notes
-----
This method calls the ``store`` method that should be overridden in subclasses
to store in the index sorted-set key | f15574:c2:m4 |
def store(self, key, pk, value): | raise NotImplementedError<EOL> | Store the value/pk in the sorted set index
Parameters
----------
key: str
The name of the sorted-set key
pk: str
The primary key of the instance having the given value
value: any
The value to use | f15574:c2:m5 |
def remove(self, *args): | key = self.get_storage_key(*args)<EOL>args = list(args)<EOL>value = args[-<NUM_LIT:1>]<EOL>pk = self.instance.pk.get()<EOL>logger.debug("<STR_LIT>" % (pk, key))<EOL>self.unstore(key, pk, self.prepare_value_for_storage(value, pk))<EOL>self._deindexed_values.add(tuple(args))<EOL> | Remove the instance tied to the field for the given "value" (via `args`) from the index
For the parameters, see ``BaseIndex.remove``
Notes
-----
This method calls the ``unstore`` method that should be overridden in subclasses
to remove data from the index sorted-set key | f15574:c2:m6 |
def unstore(self, key, pk, value): | raise NotImplementedError<EOL> | Remove the value/pk from the sorted set index
Parameters
----------
key: str
The name of the sorted-set key
pk: str
The primary key of the instance having the given value
value: any
The value to use | f15574:c2:m7 |
def get_boundaries(self, filter_type, value): | raise ImplementationError<EOL> | Compute the boundaries to pass to the sorted-set command depending of the filter type
Parameters
----------
filter_type: str
One of the filter suffixes in ``self.handled_suffixes``
value: str
The normalized value for which we want the boundaries
Returns
... | f15574:c2:m8 |
def call_script(self, key, tmp_key, key_type, start, end, exclude, *args): | self.model.database.call_script(<EOL>script_dict=self.__class__.lua_filter_script,<EOL>keys=[key, tmp_key],<EOL>args=[key_type, start, end, exclude] + list(args)<EOL>)<EOL> | Call the lua scripts with given keys and args
Parameters
-----------
key: str
The key of the index sorted-set
tmp_key: str
The final temporary key where to store the filtered primary keys
key_type: str
The type of temporary key to use, either ... | f15574:c2:m9 |
def get_filtered_keys(self, suffix, *args, **kwargs): | accepted_key_types = kwargs.get('<STR_LIT>', None)<EOL>if accepted_key_typesand '<STR_LIT>' not in accepted_key_types and '<STR_LIT>' not in accepted_key_types:<EOL><INDENT>raise ImplementationError(<EOL>'<STR_LIT>' % self.__class__.__name__<EOL>)<EOL><DEDENT>key_type = '<STR_LIT>' if not accepted_key_types or '<STR_LI... | Returns the index key for the given args "value" (`args`)
Parameters
----------
kwargs: dict
use_lua: bool
Default to ``True``, if scripting is supported.
If ``True``, the process of reading from the sorted-set, extracting
the primary ... | f15574:c2:m10 |
def get_pks_for_filter(self, key, filter_type, value): | raise NotImplementedError<EOL> | Extract the pks from the zset key for the given type and value
This is used for the uniqueness check and for the filtering if scripting
is not used
Parameters
----------
key: str
The key of the redis sorted-set to use
filter_type: str
One of ``se... | f15574:c2:m11 |
def __init__(self, field): | super(TextRangeIndex, self).__init__(field)<EOL>try:<EOL><INDENT>model = self.model<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if not self.model.database.support_zrangebylex():<EOL><INDENT>raise LimpydException(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (<EOL>'<STR_LIT:.>'.join(str(part) ... | Check that the database supports the zrangebylex redis command | f15574:c3:m0 |
def prepare_value_for_storage(self, value, pk): | value = super(TextRangeIndex, self).prepare_value_for_storage(value, pk)<EOL>return self.separator.join([value, str(pk)])<EOL> | Prepare the value to be stored in the zset
We'll store the value and pk concatenated.
For the parameters, see BaseRangeIndex.prepare_value_for_storage | f15574:c3:m1 |
def _extract_value_from_storage(self, string): | parts = string.split(self.separator)<EOL>pk = parts.pop()<EOL>return self.separator.join(parts), pk<EOL> | Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple with the value and the pk, extracted from the string | f15574:c3:m2 |
def store(self, key, pk, value): | self.connection.zadd(key, <NUM_LIT:0>, value)<EOL> | Store the value/pk in the sorted set index
For the parameters, see BaseRangeIndex.store
We add a string "value:pk" to the storage sorted-set, with a score of 0.
Then when filtering will get then lexicographical ordered
And we'll later be able to extract the pk for each returned values | f15574:c3:m3 |
def unstore(self, key, pk, value): | self.connection.zrem(key, value)<EOL> | Remove the value/pk from the sorted set index
For the parameters, see BaseRangeIndex.store | f15574:c3:m4 |
def get_boundaries(self, filter_type, value): | assert filter_type in self.handled_suffixes<EOL>start = '<STR_LIT:->'<EOL>end = '<STR_LIT:+>'<EOL>exclude = None<EOL>if filter_type in (None, '<STR_LIT>'):<EOL><INDENT>start = u'<STR_LIT>' % (value, self.separator)<EOL>end = start.encode('<STR_LIT:utf-8>') + b'<STR_LIT>'<EOL><DEDENT>elif filter_type == '<STR_LIT>':<EOL... | Compute the boundaries to pass to zrangebylex depending of the filter type
The third return value, ``exclude`` is ``None`` except for the filters
`lt` and `gt` because we cannot explicitly exclude it when
querying the sorted-set
For the parameters, see BaseRangeIndex.store
No... | f15574:c3:m5 |
def get_pks_for_filter(self, key, filter_type, value): | start, end, exclude = self.get_boundaries(filter_type, value)<EOL>members = self.connection.zrangebylex(key, start, end)<EOL>if exclude is not None:<EOL><INDENT>return [<EOL>member_pk<EOL>for member_value, member_pk in<EOL>[self._extract_value_from_storage(member) for member in members]<EOL>if member_value != exclude<E... | Extract the pks from the zset key for the given type and value
For the parameters, see BaseRangeIndex.get_pks_for_filter | f15574:c3:m6 |
def call_script(self, key, tmp_key, key_type, start, end, exclude, *args): | args = list(args)<EOL>args.append(self.separator)<EOL>super(TextRangeIndex, self).call_script(<EOL>key, tmp_key, key_type, start, end, exclude, *args<EOL>)<EOL> | Call the lua scripts with given keys and args
We add the separator to the arguments to be passed to the script
For the parameters, see BaseRangeIndex.call_script | f15574:c3:m7 |
def normalize_value(self, value, transform=True): | if transform:<EOL><INDENT>value = self.transform_value(value)<EOL><DEDENT>try:<EOL><INDENT>return float(value)<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>if self.raise_if_not_float:<EOL><INDENT>raise ValueError('<STR_LIT>' % (<EOL>value, self.model.__name__, self.field.name<EOL>))<EOL><DEDENT>return <NUM_L... | Prepare the given value to be stored in the index
For the parameters, see BaseIndex.normalize_value
Raises
------
ValueError
If ``raise_if_not_float`` is True and the value cannot
be casted to a float. | f15574:c4:m0 |
def store(self, key, pk, value): | self.connection.zadd(key, value, pk)<EOL> | Store the value/pk in the sorted set index
For the parameters, see BaseRangeIndex.store
We simple store the pk as a member of the sorted set with the value being the score | f15574:c4:m1 |
def unstore(self, key, pk, value): | self.connection.zrem(key, pk)<EOL> | Remove the value/pk from the sorted set index
For the parameters, see BaseRangeIndex.store
We simple remove the pk as a member from the sorted set | f15574:c4:m2 |
def get_boundaries(self, filter_type, value): | assert filter_type in self.handled_suffixes<EOL>start = '<STR_LIT>'<EOL>end = '<STR_LIT>'<EOL>exclude = None<EOL>if filter_type in (None, '<STR_LIT>'):<EOL><INDENT>start = end = value<EOL><DEDENT>elif filter_type == '<STR_LIT>':<EOL><INDENT>start = '<STR_LIT>' % value<EOL><DEDENT>elif filter_type == '<STR_LIT>':<EOL><I... | Compute the boundaries to pass to the sorted-set command depending of the filter type
The third return value, ``exclude`` is always ``None`` because we can easily restrict the
score to filter on in the sorted-set.
For the parameters, see BaseRangeIndex.store
Notes
-----
... | f15574:c4:m3 |
def get_pks_for_filter(self, key, filter_type, value): | start, end, __ = self.get_boundaries(filter_type, value) <EOL>return self.connection.zrangebyscore(key, start, end)<EOL> | Extract the pks from the zset key for the given type and value
For the parameters, see BaseRangeIndex.get_pks_for_filter | f15574:c4:m4 |
@staticmethod<EOL><INDENT>def class_can_have_commands(klass):<DEDENT> | try:<EOL><INDENT>return issubclass(klass, RedisProxyCommand)<EOL><DEDENT>except NameError:<EOL><INDENT>return False<EOL><DEDENT> | Return False if the given class inherits from RedisProxyCommand, which
indicates that it can handle its own sets of available commands.
If not a subclass of RedisProxyCommand, (for example "object", to create
a simple mixin), returns False. | f15575:c0:m0 |
def __new__(mcs, name, base, dct): | it = super(MetaRedisProxy, mcs).__new__(mcs, name, base, dct)<EOL>if any([mcs.class_can_have_commands(one_base) for one_base in base]):<EOL><INDENT>for attr in ('<STR_LIT>', '<STR_LIT>', ):<EOL><INDENT>setattr(it, attr, set(getattr(it, attr, ())))<EOL><DEDENT>it.available_commands = it.available_getters.union(it.availa... | Create methods for all redis commands available for the given class. | f15575:c0:m1 |
@classmethod<EOL><INDENT>def _make_command_method(cls, command_name):<DEDENT> | def func(self, *args, **kwargs):<EOL><INDENT>return self._call_command(command_name, *args, **kwargs)<EOL><DEDENT>return func<EOL> | Return a function which call _call_command for the given name.
Used to bind redis commands to our own calls | f15575:c1:m0 |
def _call_command(self, name, *args, **kwargs): | obj = getattr(self, '<STR_LIT>', self) <EOL>if name in self.available_modifiers and obj._pk and not obj.connected:<EOL><INDENT>obj.connect()<EOL><DEDENT>meth = getattr(self, '<STR_LIT>' % name, self._traverse_command)<EOL>return meth(name, *args, **kwargs)<EOL> | Check if the command to be executed is a modifier, to connect the object.
Then call _traverse_command. | f15575:c1:m1 |
def _traverse_command(self, name, *args, **kwargs): | if not name in self.available_commands:<EOL><INDENT>raise AttributeError("<STR_LIT>" %<EOL>(name, self.__class__.__name__))<EOL><DEDENT>attr = getattr(self.connection, "<STR_LIT:%s>" % name)<EOL>key = self.key<EOL>log.debug(u"<STR_LIT>" % (name, key, args))<EOL>result = attr(key, *args, **kwargs)<EOL>result = self.post... | Add the key to the args and call the Redis command. | f15575:c1:m2 |
def post_command(self, sender, name, result, args, kwargs): | return result<EOL> | Call after we got the result of a redis command.
By default, does nothing, but must return a value. | f15575:c1:m3 |
@classmethod<EOL><INDENT>def get_connection(cls):<DEDENT> | return cls.database.connection<EOL> | Return the connection from the database | f15575:c1:m4 |
@property<EOL><INDENT>def connection(self):<DEDENT> | return self.get_connection()<EOL> | A simple property on the instance that return the connection stored on
the class | f15575:c1:m5 |
def __init__(self, *args, **kwargs): | self.lockable = kwargs.get('<STR_LIT>', True)<EOL>if "<STR_LIT:default>" in kwargs:<EOL><INDENT>self.default = kwargs["<STR_LIT:default>"]<EOL><DEDENT>self.indexable = kwargs.get("<STR_LIT>", False)<EOL>self.unique = kwargs.get("<STR_LIT>", False)<EOL>if self.unique:<EOL><INDENT>if not self._unique_supported:<EOL><INDE... | Manage all field attributes | f15575:c2:m0 |
def proxy_get(self): | getter = getattr(self, self.proxy_getter)<EOL>return getter()<EOL> | A helper to easily call the proxy_getter of the field | f15575:c2:m2 |
def proxy_set(self, value): | setter = getattr(self, self.proxy_setter)<EOL>if isinstance(value, (list, tuple, set)):<EOL><INDENT>result = setter(*value)<EOL><DEDENT>elif isinstance(value, dict):<EOL><INDENT>result = setter(**value)<EOL><DEDENT>else:<EOL><INDENT>result = setter(value)<EOL><DEDENT>return result<EOL> | A helper to easily call the proxy_setter of the field | f15575:c2:m3 |
@property<EOL><INDENT>def key(self):<DEDENT> | return self.make_key(<EOL>self._instance._name,<EOL>self._instance.pk.get(),<EOL>self.name,<EOL>)<EOL> | A property to return the key used in redis for the current field. | f15575:c2:m4 |
@property<EOL><INDENT>def database(self):<DEDENT> | if not self._model:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return self._model.database<EOL> | A simple shortcut to access the database property of the field's instance | f15575:c2:m5 |
@property<EOL><INDENT>def sort_wildcard(self):<DEDENT> | return self.make_key(<EOL>self._model._name,<EOL>"<STR_LIT:*>",<EOL>self.name,<EOL>)<EOL> | Key used to sort models on this field. | f15575:c2:m6 |
@property<EOL><INDENT>def connection(self):<DEDENT> | if not self._model:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return self._model.get_connection()<EOL> | A simple shortcut to get the connections of the field's instance's model | f15575:c2:m7 |
def __copy__(self): | <EOL>args = [getattr(self, arg) for arg in self._copy_conf['<STR_LIT:args>']]<EOL>kwargs = {}<EOL>for arg in self._copy_conf['<STR_LIT>']:<EOL><INDENT>name = arg<EOL>if isinstance(arg, tuple):<EOL><INDENT>name, arg = arg<EOL><DEDENT>if hasattr(self, arg):<EOL><INDENT>kwargs[name] = getattr(self, arg)<EOL><DEDENT><DEDEN... | In the RedisModel metaclass and constructor, we need to copy the fields
to new ones. It can be done via the copy function of the copy module.
This __copy__ method handles the copy by creating a new field with same
attributes, without ignoring private attributes.
Configuration of args and kwargs to pass to the construct... | f15575:c2:m8 |
def make_key(self, *args): | return make_key(*args)<EOL> | Simple shortcut to the make_key global function to create a redis key
based on all given arguments. | f15575:c2:m9 |
def delete(self): | return self._call_command('<STR_LIT>')<EOL> | Delete the field from redis. | f15575:c2:m10 |
def post_command(self, sender, name, result, args, kwargs): | return self._instance.post_command(<EOL>sender=self,<EOL>name=name,<EOL>result=result,<EOL>args=args,<EOL>kwargs=kwargs<EOL>)<EOL> | Call after we got the result of a redis command.
By default, let the instance manage the post_modify signal | f15575:c2:m11 |
def exists(self): | try:<EOL><INDENT>key = self.key<EOL><DEDENT>except DoesNotExist:<EOL><INDENT>"""<STR_LIT>"""<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>return self.connection.exists(key)<EOL><DEDENT> | Call the exists command to check if the redis key exists for the current
field | f15575:c2:m12 |
@cached_property<EOL><INDENT>def _indexes(self):<DEDENT> | if not self.indexable:<EOL><INDENT>return []<EOL><DEDENT>if not self.index_classes:<EOL><INDENT>self.index_classes = self.get_default_indexes()[::<NUM_LIT:1>]<EOL><DEDENT>if not self.index_classes:<EOL><INDENT>raise ImplementationError('<STR_LIT>' %<EOL>self.__class__.__name__)<EOL><DEDENT>return [index_class(field=sel... | Instantiate the indexes only when asked
Returns
-------
list
An empty list if the field is not indexable, else a list of all indexes
tied to the field.
If no indexes where passed when creating the field, the default indexes
from the field/model/da... | f15575:c2:m13 |
def has_index(self, index): | klass = index if isclass(index) else index.__class__<EOL>for one_index in self._indexes:<EOL><INDENT>if isinstance(one_index, klass):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Tells if the field have an index matching the current one
Parameters
-----------
index: type or BaseIndex
It could be an index instance, or an index class
Returns
-------
bool
Will be ``True`` if the current field has an index that is an instance... | f15575:c2:m14 |
def _attach_to_model(self, model): | self._model = model<EOL> | Attach the current field to a model. Can be overriden to do something
when a model is set | f15575:c2:m15 |
def _attach_to_instance(self, instance): | self._instance = instance<EOL>self.lockable = self.lockable and instance.lockable<EOL> | Attach the current field to an instance of a model. Can be overriden to
do something when an instance is set | f15575:c2:m16 |
@property<EOL><INDENT>def attached_to_model(self):<DEDENT> | try:<EOL><INDENT>if not bool(self._model):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return not bool(self._instance)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return True<EOL><DEDENT><DEDENT> | Tells if the current field is the one attached to the model, not instance | f15575:c2:m17 |
def _call_command(self, name, *args, **kwargs): | meth = super(RedisField, self)._call_command<EOL>if self.indexable and name in self.available_modifiers:<EOL><INDENT>with FieldLock(self):<EOL><INDENT>try:<EOL><INDENT>result = meth(name, *args, **kwargs)<EOL><DEDENT>except:<EOL><INDENT>self._rollback_indexes()<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>return result<EOL>... | Add lock management and call parent. | f15575:c2:m18 |
def _rollback_indexes(self): | for index in self._indexes:<EOL><INDENT>index._rollback()<EOL><DEDENT> | Restore the index in its previous status, using deindexed/indexed values
temporarily stored. | f15575:c2:m19 |
def _reset_indexes_caches(self): | for index in self._indexes:<EOL><INDENT>index._reset_cache()<EOL><DEDENT> | Reset attributes used to store deindexed/indexed values, used to
rollback the index when something failed. | f15575:c2:m20 |
def index(self, value=None, only_index=None): | assert self.indexable, "<STR_LIT>"<EOL>assert not only_index or self.has_index(only_index), "<STR_LIT>"<EOL>if only_index:<EOL><INDENT>only_index = only_index if isclass(only_index) else only_index.__class__<EOL><DEDENT>if value is None:<EOL><INDENT>value = self.proxy_get()<EOL><DEDENT>if value is not None:<EOL><INDENT... | Handle field index process. | f15575:c2:m21 |
def deindex(self, value=None, only_index=None): | assert self.indexable, "<STR_LIT>"<EOL>assert not only_index or self.has_index(only_index), "<STR_LIT>"<EOL>if only_index:<EOL><INDENT>only_index = only_index if isclass(only_index) else only_index.__class__<EOL><DEDENT>if value is None:<EOL><INDENT>value = self.proxy_get()<EOL><DEDENT>if value is not None:<EOL><INDENT... | Run process of deindexing field value(s). | f15575:c2:m22 |
def clear_indexes(self, chunk_size=<NUM_LIT:1000>, aggressive=False, index_class=None): | assert self.indexable, "<STR_LIT>"<EOL>assert self.attached_to_model,'<STR_LIT>'<EOL>for index in self._indexes:<EOL><INDENT>if index_class and not isinstance(index, index_class):<EOL><INDENT>continue<EOL><DEDENT>index.clear(chunk_size=chunk_size, aggressive=aggressive)<EOL><DEDENT> | Clear all indexes tied to this field
Parameters
----------
chunk_size: int
Default to 1000, it's the number of instances to load at once if not in aggressive mode.
aggressive: bool
Default to ``False``. When ``False``, the actual collection of instances will
... | f15575:c2:m23 |
def rebuild_indexes(self, chunk_size=<NUM_LIT:1000>, aggressive_clear=False, index_class=None): | assert self.indexable, "<STR_LIT>"<EOL>assert self.attached_to_model,'<STR_LIT>'<EOL>for index in self._indexes:<EOL><INDENT>if index_class and not isinstance(index, index_class):<EOL><INDENT>continue<EOL><DEDENT>index.rebuild(chunk_size=chunk_size, aggressive_clear=aggressive_clear)<EOL><DEDENT> | Rebuild all indexes tied to this field
Parameters
----------
chunk_size: int
Default to 1000, it's the number of instances to load at once.
aggressive_clear: bool
Will be passed to the `aggressive` argument of the `clear_indexes` method.
If `False`, a... | f15575:c2:m24 |
def from_python(self, value): | return normalize(value)<EOL> | Coerce a value before using it in Redis. | f15575:c2:m27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.