signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def _reset(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.deindex()<EOL><DEDENT>result = self._traverse_command(command, *args, **kwargs)<EOL>if self.indexable:<EOL><INDENT>self.index()<EOL><DEDENT>return result<EOL> | Shortcut for commands that reset values of the field.
All will be deindexed and reindexed. | f15575:c2:m28 |
def _reindex_from_result(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.deindex()<EOL><DEDENT>result = self._traverse_command(command, *args, **kwargs)<EOL>if self.indexable and result is not None:<EOL><INDENT>self.index(result)<EOL><DEDENT>return result<EOL> | Same as _reset, but uses Redis return value to reindex, to
save one query. | f15575:c2:m29 |
def _del(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.deindex()<EOL><DEDENT>return self._traverse_command(command, *args, **kwargs)<EOL> | Shortcut for commands that remove all values of the field.
All will be deindexed. | f15575:c2:m30 |
def _call_set(self, command, value, *args, **kwargs): | if self.indexable:<EOL><INDENT>current = self.proxy_get()<EOL>if normalize(current) != normalize(value):<EOL><INDENT>if current is not None:<EOL><INDENT>self.deindex(current)<EOL><DEDENT>if value is not None:<EOL><INDENT>self.index(value)<EOL><DEDENT><DEDENT><DEDENT>return self._traverse_command(command, value, *args, **kwargs)<EOL> | Helper for commands that only set a value to the field. | f15575:c3:m0 |
def _call_setnx(self, command, value): | result = self._traverse_command(command, value)<EOL>if self.indexable and value is not None and result:<EOL><INDENT>self.index(value)<EOL><DEDENT>return result<EOL> | Index only if value has been set. | f15575:c4:m0 |
def _add(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.index(args)<EOL><DEDENT>return self._traverse_command(command, *args, **kwargs)<EOL> | Shortcut for commands that only add values to the field.
Added values will be indexed. | f15575:c5:m0 |
def _rem(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.deindex(args)<EOL><DEDENT>return self._traverse_command(command, *args, **kwargs)<EOL> | Shortcut for commands that only remove values from the field.
Removed values will be deindexed. | f15575:c5:m1 |
def _pop(self, command, *args, **kwargs): | result = self._traverse_command(command, *args, **kwargs)<EOL>if self.indexable:<EOL><INDENT>self.deindex([result])<EOL><DEDENT>return result<EOL> | Shortcut for commands that pop a value from the field, returning it while
removing it.
The returned value will be deindexed | f15575:c5:m2 |
def index(self, values=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 values is None:<EOL><INDENT>values = self.proxy_get()<EOL><DEDENT>for value in values:<EOL><INDENT>if value is not None:<EOL><INDENT>needs_to_check_uniqueness = bool(self.unique)<EOL>for index in self._indexes:<EOL><INDENT>if only_index and not isinstance(index, only_index):<EOL><INDENT>continue<EOL><DEDENT>index.add(value, check_uniqueness=needs_to_check_uniqueness and index.handle_uniqueness)<EOL>if needs_to_check_uniqueness and index.handle_uniqueness:<EOL><INDENT>needs_to_check_uniqueness = False<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Index all values stored in the field, or only given ones if any. | f15575:c5:m3 |
def deindex(self, values=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 not values:<EOL><INDENT>values = self.proxy_get()<EOL><DEDENT>for value in values:<EOL><INDENT>if value is not None:<EOL><INDENT>for index in self._indexes:<EOL><INDENT>if only_index and not isinstance(index, only_index):<EOL><INDENT>continue<EOL><DEDENT>index.remove(value)<EOL><DEDENT><DEDENT><DEDENT> | Deindex all values stored in the field, or only given ones if any. | f15575:c5:m4 |
def zmembers(self): | return self.zrange(<NUM_LIT:0>, -<NUM_LIT:1>)<EOL> | Used as a proxy_getter to get all values stored in the field. | f15575:c6:m0 |
def _call_zadd(self, command, *args, **kwargs): | if self.indexable:<EOL><INDENT>keys = []<EOL>if args:<EOL><INDENT>if len(args) % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>raise RedisError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>keys.extend(args[<NUM_LIT:1>::<NUM_LIT:2>])<EOL><DEDENT>keys.extend(kwargs) <EOL>self.index(keys)<EOL><DEDENT>return self._traverse_command(command, *args, **kwargs)<EOL> | We do the same computation of the zadd method of StrictRedis to keep keys
to index them (instead of indexing the whole set)
Members (value/score) can be passed:
- in *args, with score followed by the value, 0+ times (to respect
the redis order)
- in **kwargs, with value as key and score as value
Example: zadd(1.1, 'my-key', 2.2, 'name1', 'name2', name3=3.3, name4=4.4) | f15575:c6:m1 |
def _call_zincrby(self, command, value, *args, **kwargs): | if self.indexable:<EOL><INDENT>self.index([value])<EOL><DEDENT>return self._traverse_command(command, value, *args, **kwargs)<EOL> | This command update a score of a given value. But it can be a new value
of the sorted set, so we index it. | f15575:c6:m2 |
@staticmethod<EOL><INDENT>def coerce_zadd_args(*args, **kwargs):<DEDENT> | values_callback = kwargs.pop('<STR_LIT>', None)<EOL>pieces = []<EOL>if args:<EOL><INDENT>if len(args) % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>raise RedisError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>pieces.extend(args)<EOL><DEDENT>for pair in iteritems(kwargs):<EOL><INDENT>pieces.append(pair[<NUM_LIT:1>])<EOL>pieces.append(pair[<NUM_LIT:0>])<EOL><DEDENT>values = pieces[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>if values_callback:<EOL><INDENT>values = values_callback(*values)<EOL><DEDENT>scores = pieces[<NUM_LIT:0>::<NUM_LIT:2>]<EOL>pieces = []<EOL>for z in zip(scores, values):<EOL><INDENT>pieces.extend(z)<EOL><DEDENT>return pieces<EOL> | Take arguments attended by a zadd call, named or not, and return a flat list
that can be used.
A callback can be called with all "values" (as *args) if defined as the
`values_callback` named argument. Real values will then be the result of
this callback. | f15575:c6:m3 |
def lmembers(self): | return self.lrange(<NUM_LIT:0>, -<NUM_LIT:1>)<EOL> | Used as a proxy_getter to get all values stored in the field. | f15575:c8:m0 |
def _pushx(self, command, *args, **kwargs): | result = self._traverse_command(command, *args, **kwargs)<EOL>if self.indexable and result:<EOL><INDENT>self.index(args)<EOL><DEDENT>return result<EOL> | Helper for lpushx and rpushx, that only index the new values if the list
existed when the command was called | f15575:c8:m1 |
def _call_lrem(self, command, count, value, *args, **kwargs): | if not count:<EOL><INDENT>if self.indexable:<EOL><INDENT>self.deindex([value])<EOL><DEDENT>return self._traverse_command(command, count, value, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return self._reset(command, count, value, *args, **kwargs)<EOL><DEDENT> | If count is 0, we remove all elements equal to value, so we know we have
nothing to index, and this value to deindex. In other case, we don't
know how much elements will remain in the list, so we have to do a full
deindex/reindex. So do it carefuly. | f15575:c8:m2 |
def _call_lset(self, command, index, value, *args, **kwargs): | if self.indexable:<EOL><INDENT>old_value = self.lindex(index)<EOL>self.deindex([old_value])<EOL><DEDENT>result = self._traverse_command(command, index, value, *args, **kwargs)<EOL>if self.indexable:<EOL><INDENT>self.index([value])<EOL><DEDENT>return result<EOL> | Before setting the new value, get the previous one to deindex it. Then
call the command and index the new value, if exists | f15575:c8:m3 |
def index(self, values=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 values is None:<EOL><INDENT>values = self.proxy_get()<EOL><DEDENT>for field_name, value in iteritems(values):<EOL><INDENT>if value is not None:<EOL><INDENT>needs_to_check_uniqueness = bool(self.unique)<EOL>for index in self._indexes:<EOL><INDENT>if only_index and not isinstance(index, only_index):<EOL><INDENT>continue<EOL><DEDENT>index.add(field_name, value, check_uniqueness=needs_to_check_uniqueness and index.handle_uniqueness)<EOL>if needs_to_check_uniqueness and index.handle_uniqueness:<EOL><INDENT>needs_to_check_uniqueness = False<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Deal with dicts and field names. | f15575:c9:m6 |
def deindex(self, values=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 values is None:<EOL><INDENT>values = self.proxy_get()<EOL><DEDENT>for field_name, value in iteritems(values):<EOL><INDENT>if value is not None:<EOL><INDENT>for index in self._indexes:<EOL><INDENT>if only_index and not isinstance(index, only_index):<EOL><INDENT>continue<EOL><DEDENT>index.remove(field_name, value)<EOL><DEDENT><DEDENT><DEDENT> | Deal with dicts and field names. | f15575:c9:m7 |
def hexists(self, key): | try:<EOL><INDENT>hashkey = self.key<EOL><DEDENT>except DoesNotExist:<EOL><INDENT>"""<STR_LIT>"""<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>return self.connection.hexists(hashkey, key)<EOL><DEDENT> | Call the hexists command to check if the redis hash key exists for the
current field | f15575:c9:m8 |
def _traverse_command(self, name, *args, **kwargs): | args = list(args)<EOL>args.insert(<NUM_LIT:0>, self.name)<EOL>return super(InstanceHashField, self)._traverse_command(name, *args, **kwargs)<EOL> | Add key AND the hash field to the args, and call the Redis command. | f15575:c10:m2 |
def delete(self): | return self._call_command('<STR_LIT>')<EOL> | Delete the field from redis, only the hash entry | f15575:c10:m3 |
def hexists(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.hexists(key, self.name)<EOL><DEDENT> | Call the hexists command to check if the redis hash key exists for the
current field | f15575:c10:m4 |
def normalize(self, value): | return str(value)<EOL> | Simple method to always have the same kind of value
It can be overriden by converting to int | f15575:c11:m0 |
def _validate(self, value): | if value is None:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>self._model.__name__)<EOL><DEDENT>value = self.normalize(value)<EOL>if self.exists(value):<EOL><INDENT>raise UniquenessError('<STR_LIT>' %<EOL>(value, self._instance.__class__))<EOL><DEDENT>return value<EOL> | Validate that a given new pk to set is always set, and return it.
The returned value should be normalized, and will be used without check. | f15575:c11:m1 |
@property<EOL><INDENT>def collection_key(self):<DEDENT> | return '<STR_LIT>' % self._model._name<EOL> | Property that return the name of the key in Redis where are stored
all the exinsting pk for the model hosting this PKField | f15575:c11:m2 |
def exists(self, value=None): | try:<EOL><INDENT>if not value:<EOL><INDENT>value = self.get()<EOL><DEDENT><DEDENT>except (AttributeError, DoesNotExist):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return self.connection.sismember(self.collection_key, value)<EOL><DEDENT> | Return True if the given pk value exists for the given class.
If no value is given, we use the value of the current field, which
is the value of the "_pk" attribute of its instance. | f15575:c11:m3 |
def collection(self): | return self.connection.smembers(self.collection_key)<EOL> | Return all available primary keys for the given class | f15575:c11:m4 |
def set(self, value): | <EOL>if self._set:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>value = self._validate(value)<EOL>self._instance._set_pk(value)<EOL>self._set = True<EOL>log.debug("<STR_LIT>" % (value, self._model._name))<EOL>self.connection.sadd(self.collection_key, value)<EOL>return <NUM_LIT:1><EOL> | Override the default setter to check uniqueness, deny updating, and add
the new pk to the model's collection.
The value is not saved as a field in redis, because we don't need this.
On an instance, we have the _pk attribute with the pk value, and when
we ask for a collection, we get somes pks which can be used to instanciate
new objects (holding the pk value in _pk) | f15575:c11:m5 |
def get(self): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>raise ImplementationError("<STR_LIT>")<EOL><DEDENT>if not hasattr(self._instance, '<STR_LIT>'):<EOL><INDENT>raise DoesNotExist("<STR_LIT>")<EOL><DEDENT>if not self._instance._pk:<EOL><INDENT>self.set(value=None)<EOL><DEDENT>return self.normalize(self._instance._pk)<EOL> | We do not call the default getter as we have the value cached in the
instance in its _pk attribute | f15575:c11:m6 |
def _validate(self, value): | if value is not None:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>self._model.__name__)<EOL><DEDENT>key = self._instance.make_key(self._model._name, '<STR_LIT>')<EOL>return self.normalize(self.connection.incr(key))<EOL> | Validate that a given new pk to set is always set to None, then return
a new pk | f15575:c12:m0 |
def __init__(self, field, timeout=<NUM_LIT:5>, sleep=<NUM_LIT:0.1>): | self.field = field<EOL>self.sub_lock_mode = False<EOL>super(FieldLock, self).__init__(<EOL>redis=field._model.get_connection(),<EOL>name=make_key(field._model._name, '<STR_LIT>', field.name),<EOL>timeout=timeout,<EOL>sleep=sleep,<EOL>)<EOL> | Save the field and create a real lock,, using the correct connection
and a computed lock key based on the names of the field and its model. | f15575:c13:m0 |
def _get_already_locked_by_model(self): | return self.field._model._is_field_locked(self.field)<EOL> | A lock is self_locked if already set for the current field+model on the current
thread. | f15575:c13:m1 |
def acquire(self, *args, **kwargs): | if not self.field.lockable:<EOL><INDENT>return<EOL><DEDENT>if self.already_locked_by_model:<EOL><INDENT>self.sub_lock_mode = True<EOL>return<EOL><DEDENT>self.already_locked_by_model = True<EOL>super(FieldLock, self).acquire(*args, **kwargs)<EOL> | Really acquire the lock only if it's not a sub-lock. Then save the
sub-lock status. | f15575:c13:m3 |
def release(self, *args, **kwargs): | if not self.field.lockable:<EOL><INDENT>return<EOL><DEDENT>if self.sub_lock_mode:<EOL><INDENT>return<EOL><DEDENT>super(FieldLock, self).release(*args, **kwargs)<EOL>self.already_locked_by_model = self.sub_lock_mode = False<EOL> | Really release the lock only if it's not a sub-lock. Then save the
sub-lock status and mark the model as unlocked. | f15575:c13:m4 |
def __exit__(self, *args, **kwargs): | super(FieldLock, self).__exit__(*args, **kwargs)<EOL>if not self.field.lockable:<EOL><INDENT>return<EOL><DEDENT>if not self.sub_lock_mode:<EOL><INDENT>self.already_locked_by_model = False<EOL><DEDENT> | Mark the model as unlocked. | f15575:c13:m5 |
def _optimize_slice(self, the_slice, can_reverse): | step = <NUM_LIT:1> if the_slice.step in (<NUM_LIT:1>, None) else the_slice.step<EOL>start = (the_slice.start or <NUM_LIT:0>) if step > <NUM_LIT:0> else the_slice.start<EOL>stop = the_slice.stop<EOL>if start is not None and stop is not None:<EOL><INDENT>if step > <NUM_LIT:0> and (<NUM_LIT:0> <= stop <= start or stop <= start < <NUM_LIT:0>):<EOL><INDENT>return True, None, None, False, NONE_SLICE<EOL><DEDENT>if step < <NUM_LIT:0> and (<NUM_LIT:0> <= start <= stop or start <= stop < <NUM_LIT:0>):<EOL><INDENT>return True, None, None, False, NONE_SLICE<EOL><DEDENT>if start >= <NUM_LIT:0> and stop > <NUM_LIT:0>:<EOL><INDENT>if step < <NUM_LIT:0>:<EOL><INDENT>start, stop = stop + <NUM_LIT:1>, start + <NUM_LIT:1><EOL><DEDENT>return True, start, stop - start, False, slice(None, None, step if step != <NUM_LIT:1> else None)<EOL><DEDENT>if start < <NUM_LIT:0> and stop < <NUM_LIT:0> and can_reverse:<EOL><INDENT>if step < <NUM_LIT:0>:<EOL><INDENT>start, stop = stop + <NUM_LIT:1>, start + <NUM_LIT:1><EOL><DEDENT>step = -step<EOL>return True, - stop, stop - start, True, slice(None, None, step if step != <NUM_LIT:1> else None)<EOL><DEDENT><DEDENT>if step > <NUM_LIT:0> and (start is not None and start >= <NUM_LIT:0>) and (stop is None or stop < <NUM_LIT:0>):<EOL><INDENT>return True, start, None, False, slice(None, stop, step)<EOL><DEDENT>if step < <NUM_LIT:0> and (start is None or start < <NUM_LIT:0>) and (stop is not None and stop >= <NUM_LIT:0>):<EOL><INDENT>return True, stop + <NUM_LIT:1>, None, False, slice(start, None, step)<EOL><DEDENT>return False, None, None, False, slice(start, stop, step)<EOL> | Parameters
----------
the_slice: slice
The python slice to optimize
can_reverse: bool
If we can ask redis to reverse the data before slicing.
Returns
-------
tuple
Four elements:
- optimized: bool
If the slice is optimized
- start: int or None
start item to pass to the redis command
If None, we want from the very start
- count: int or None
number of items to ask the redi command
If None, we want everything from the start
- rev: bool
If we should ask redis to work the reverse way
- python_slice
The slice to be applied on the python side | f15576:c0:m2 |
def _get_pk(self): | pk = None<EOL>if self._lazy_collection['<STR_LIT>']:<EOL><INDENT>if len(self._lazy_collection['<STR_LIT>']) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>pk = list(self._lazy_collection['<STR_LIT>'])[<NUM_LIT:0>]<EOL><DEDENT>return pk<EOL> | Return None if we don't have any filter on a pk, the pk if we have one,
or raise a ValueError if we have more than one.
For internal use only. | f15576:c0:m4 |
def _prepare_sort_options(self, has_pk): | sort_options = {}<EOL>if self._sort is not None and not has_pk:<EOL><INDENT>sort_options.update(self._sort)<EOL><DEDENT>if self._sort_limits is not None:<EOL><INDENT>if '<STR_LIT:start>' in self._sort_limits and '<STR_LIT>' not in self._sort_limits:<EOL><INDENT>self._sort_limits['<STR_LIT>'] = -<NUM_LIT:1><EOL><DEDENT>elif '<STR_LIT>' in self._sort_limits and '<STR_LIT:start>' not in self._sort_limits:<EOL><INDENT>self._sort_limits['<STR_LIT:start>'] = <NUM_LIT:0><EOL><DEDENT>sort_options.update(self._sort_limits)<EOL><DEDENT>if not sort_options and self._sort is None:<EOL><INDENT>sort_options = None<EOL><DEDENT>return sort_options<EOL> | Prepare "sort" options to use when calling the collection, depending
on "_sort" and "_sort_limits" attributes | f15576:c0:m5 |
@property<EOL><INDENT>def _collection(self):<DEDENT> | old_sort_limits_and_len_mode = None if self._sort_limits is None else self._sort_limits.copy(), self._len_mode<EOL>try: <EOL><INDENT>conn = self.cls.get_connection()<EOL>self._len = <NUM_LIT:0><EOL>try:<EOL><INDENT>pk = self._get_pk()<EOL><DEDENT>except ValueError:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>if pk is not None and not self.cls.get_field('<STR_LIT>').exists(pk):<EOL><INDENT>return []<EOL><DEDENT><DEDENT>sort_options = self._prepare_sort_options(bool(pk))<EOL>final_set, keys_to_delete = self._get_final_set(<EOL>self._lazy_collection['<STR_LIT>'],<EOL>pk, sort_options)<EOL>if self._len_mode:<EOL><INDENT>if final_set is None:<EOL><INDENT>if pk and not self._lazy_collection['<STR_LIT>']:<EOL><INDENT>self._len = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._len = <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._len = self._collection_length(final_set)<EOL>if keys_to_delete:<EOL><INDENT>conn.delete(*keys_to_delete)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>else:<EOL><INDENT>if final_set is None:<EOL><INDENT>if pk and not self._lazy_collection['<STR_LIT>']:<EOL><INDENT>collection = {pk}<EOL><DEDENT>else:<EOL><INDENT>collection = {}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>collection = self._final_redis_call(final_set, sort_options)<EOL>if keys_to_delete:<EOL><INDENT>conn.delete(*keys_to_delete)<EOL><DEDENT><DEDENT>return self._prepare_results(collection)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self._sort_limits, self._len_mode = old_sort_limits_and_len_mode<EOL><DEDENT> | Effectively retrieve data according to lazy_collection. | f15576:c0:m6 |
def _final_redis_call(self, final_set, sort_options): | conn = self.cls.get_connection()<EOL>if sort_options is not None:<EOL><INDENT>return conn.sort(final_set, **sort_options)<EOL><DEDENT>else:<EOL><INDENT>return conn.smembers(final_set)<EOL><DEDENT> | The final redis call to obtain the values to return from the "final_set"
with some sort options. | f15576:c0:m7 |
def _collection_length(self, final_set): | return self.cls.get_connection().scard(final_set)<EOL> | Return the length of the final collection, directly asking redis for the
count without calling sort | f15576:c0:m8 |
def _to_instances(self, pks): | <EOL>meth = self.cls.lazy_connect if self._instances_skip_exist_test else self.cls<EOL>return [meth(pk) for pk in pks]<EOL> | Returns a list of instances for each given pk, respecting the condition
about checking or not if a pk exists. | f15576:c0:m9 |
def _prepare_results(self, results): | if self._instances:<EOL><INDENT>results = self._to_instances(results)<EOL><DEDENT>else:<EOL><INDENT>results = list(results)<EOL><DEDENT>self._len = len(results)<EOL>return results<EOL> | Called in _collection to prepare results from redis before returning
them. | f15576:c0:m10 |
def _prepare_sets(self, sets): | final_sets = set()<EOL>tmp_keys = set()<EOL>for set_ in sets:<EOL><INDENT>if isinstance(set_, str):<EOL><INDENT>final_sets.add(set_)<EOL><DEDENT>elif isinstance(set_, ParsedFilter):<EOL><INDENT>for index_key, key_type, is_tmp in set_.index.get_filtered_keys(<EOL>set_.suffix,<EOL>accepted_key_types=self._accepted_key_types,<EOL>*(set_.extra_field_parts + [set_.value])<EOL>):<EOL><INDENT>if key_type not in self._accepted_key_types:<EOL><INDENT>raise ValueError('<STR_LIT>' % (<EOL>set_.index.__class__.__name__<EOL>))<EOL><DEDENT>final_sets.add(index_key)<EOL>if is_tmp:<EOL><INDENT>tmp_keys.add(index_key)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>return final_sets, tmp_keys<EOL> | Return all sets in self._lazy_collection['sets'] to be ready to be used
to intersect them. Called by _get_final_set, to use in subclasses.
Must return a tuple with a set of redis set keys, and another with
new temporary keys to drop at the end of _get_final_set | f15576:c0:m11 |
def _get_final_set(self, sets, pk, sort_options): | conn = self.cls.get_connection()<EOL>all_sets = set()<EOL>tmp_keys = set()<EOL>if pk is not None and not sets and not (sort_options and sort_options.get('<STR_LIT>')):<EOL><INDENT>return (None, False)<EOL><DEDENT>elif sets or pk:<EOL><INDENT>if sets:<EOL><INDENT>new_sets, new_tmp_keys = self._prepare_sets(sets)<EOL>all_sets.update(new_sets)<EOL>tmp_keys.update(new_tmp_keys)<EOL><DEDENT>if pk is not None:<EOL><INDENT>tmp_key = self._unique_key()<EOL>conn.sadd(tmp_key, pk)<EOL>all_sets.add(tmp_key)<EOL>tmp_keys.add(tmp_key)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>all_sets.add(self.cls.get_field('<STR_LIT>').collection_key)<EOL><DEDENT>if not all_sets:<EOL><INDENT>delete_set_later = False<EOL>final_set = None<EOL><DEDENT>elif len(all_sets) == <NUM_LIT:1>:<EOL><INDENT>final_set = all_sets.pop()<EOL>if final_set in tmp_keys:<EOL><INDENT>delete_set_later = True<EOL>tmp_keys.remove(final_set)<EOL><DEDENT>else:<EOL><INDENT>delete_set_later = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>delete_set_later = True<EOL>final_set = self._combine_sets(all_sets, self._unique_key())<EOL><DEDENT>if tmp_keys:<EOL><INDENT>conn.delete(*tmp_keys)<EOL><DEDENT>return (final_set, [final_set] if delete_set_later else None)<EOL> | Called by _collection to get the final set to work on. Return the name
of the set to use, and a list of keys to delete once the collection is
really called (in case of a computed set based on multiple ones) | f15576:c0:m12 |
def _combine_sets(self, sets, final_set): | self.cls.get_connection().sinterstore(final_set, list(sets))<EOL>return final_set<EOL> | Given a list of set, combine them to create the final set that will be
used to make the final redis call. | f15576:c0:m13 |
def _field_is_pk(self, field_name): | if self.cls._field_is_pk(field_name):<EOL><INDENT>return True<EOL><DEDENT>if field_name.endswith('<STR_LIT>') and self.cls._field_is_pk(field_name[:-<NUM_LIT:4>]):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Check if the given name is the pk field, suffixed or not with "__eq | f15576:c0:m15 |
def _add_filters(self, **filters): | for key, value in filters.items():<EOL><INDENT>if self._field_is_pk(key):<EOL><INDENT>pk = self.cls.get_field('<STR_LIT>').normalize(value)<EOL>self._lazy_collection['<STR_LIT>'].add(pk)<EOL><DEDENT>else:<EOL><INDENT>index, suffix, extra_field_parts = self._parse_filter_key(key)<EOL>parsed_filter = ParsedFilter(index, suffix, extra_field_parts, value)<EOL>self._lazy_collection['<STR_LIT>'].append(parsed_filter)<EOL><DEDENT><DEDENT>return self<EOL> | Define self._lazy_collection according to filters. | f15576:c0:m17 |
def _get_simple_fields(self): | fields = []<EOL>for field_name in self.cls._fields:<EOL><INDENT>field = self.cls.get_field(field_name)<EOL>if not isinstance(field, MultiValuesField):<EOL><INDENT>fields.append(field_name)<EOL><DEDENT><DEDENT>return fields<EOL> | Return a list of the names of all fields that handle simple values
(StringField or InstanceHashField), that redis can use to return values via
the sort command (so, exclude all fields based on MultiValuesField) | f15576:c0:m21 |
def primary_keys(self): | self.reset_result_type()<EOL>return self<EOL> | Ask the collection to return a list of primary keys. It's the default
but if `instances`, `values` or `values_list` was previously called,
a call to `primary_keys` restore this default behaviour. | f15576:c0:m22 |
def reset_result_type(self): | self._instances = False<EOL> | Reset the type of values attened for the collection (ie cancel a
previous "instances" call) | f15576:c0:m23 |
def sort(self, **parameters): | parameters = self._coerce_by_parameter(parameters)<EOL>self._sort = parameters<EOL>return self<EOL> | Parameters:
`by`: pass either a field name or a wildcard string to sort on
prefix with `-` to make a desc sort.
`alpha`: set it to True to sort lexicographically instead of numerically. | f15576:c0:m25 |
def _unique_key(self): | return unique_key(self.cls.get_connection())<EOL> | Create a unique key. | f15576:c0:m26 |
def make_key(*args): | return u"<STR_LIT::>".join(str(arg) for arg in args)<EOL> | Create the key concatening all args with `:`. | f15578:m0 |
def unique_key(connection): | while <NUM_LIT:1>:<EOL><INDENT>key = str(uuid.uuid4().hex)<EOL>if not connection.exists(key):<EOL><INDENT>break<EOL><DEDENT><DEDENT>return key<EOL> | Generate a unique keyname that does not exists is the connection
keyspace. | f15578:m1 |
def normalize(value): | if value and isinstance(value, bytes):<EOL><INDENT>value = value.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return value<EOL> | Simple method to always have the same kind of value | f15578:m2 |
def connect(self, **settings): | <EOL>if not settings:<EOL><INDENT>settings = self.connection_settings<EOL><DEDENT>connection_key = '<STR_LIT::>'.join([str(settings[k]) for k in sorted(settings)])<EOL>if connection_key not in self._connections:<EOL><INDENT>self._connections[connection_key] = redis.StrictRedis(<EOL>decode_responses=True, **settings)<EOL><DEDENT>return self._connections[connection_key]<EOL> | Connect to redis and cache the new connection | f15579:c0:m2 |
def reset(self, **connection_settings): | self.connection_settings = connection_settings<EOL>self._connection = None<EOL> | Set the new connection settings to be used and reset the connection
cache so the next redis call will use these settings. | f15579:c0:m3 |
def _add_model(self, model): | name = model._name<EOL>existing = self._models.get(name, None)<EOL>if not existing:<EOL><INDENT>self._models[name] = model<EOL><DEDENT>elif model.__name__ != existing.__name__ or model._creation_source != existing._creation_source:<EOL><INDENT>raise ImplementationError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (model.namespace, model.__name__))<EOL><DEDENT>return self._models[name]<EOL> | Save this model as one existing on this database, to deny many models
with same namespace and name.
If the model already exists, check if it is the same. It can happen if the
module is imported twice in different ways.
If it's a new model or an existing and valid one, return the model in database: the
one added or the existing one | f15579:c0:m4 |
def _use_for_model(self, model): | original_database = getattr(model, '<STR_LIT>', None)<EOL>def get_models(model):<EOL><INDENT>"""<STR_LIT>"""<EOL>model_database = getattr(model, '<STR_LIT>', None)<EOL>if model_database == self:<EOL><INDENT>return []<EOL><DEDENT>models = [model]<EOL>for submodel in model.__subclasses__():<EOL><INDENT>if getattr(submodel, '<STR_LIT>', None) == model_database:<EOL><INDENT>models += get_models(submodel)<EOL><DEDENT><DEDENT>return models<EOL><DEDENT>models = get_models(model)<EOL>for _model in models:<EOL><INDENT>if not _model.abstract:<EOL><INDENT>self._add_model(_model)<EOL>del original_database._models[_model._name]<EOL><DEDENT>_model.database = self<EOL><DEDENT>return models<EOL> | Update the given model to use the current database. Do it also for all
of its subclasses if they share the same database. (so it's easy to
call use_database on an abstract model to use the new database for all
subclasses) | f15579:c0:m5 |
@property<EOL><INDENT>def connection(self):<DEDENT> | if self._connection is None:<EOL><INDENT>self._connection = self.connect()<EOL><DEDENT>return self._connection<EOL> | A simple property on the instance that return the connection stored on
the class | f15579:c0:m6 |
@property<EOL><INDENT>def redis_version(self):<DEDENT> | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._redis_version = tuple(<EOL>map(int, self.connection.info().get('<STR_LIT>').split('<STR_LIT:.>')[:<NUM_LIT:3>])<EOL>)<EOL><DEDENT>return self._redis_version<EOL> | Return the redis version as a tuple | f15579:c0:m7 |
def support_scripting(self): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>self._support_scripting = self.redis_version >= (<NUM_LIT:2>, <NUM_LIT:5>)and hasattr(self.connection, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>self._support_scripting = False<EOL><DEDENT><DEDENT>return self._support_scripting<EOL> | Returns True if scripting is available. Checks are done in the client
library (redis-py) AND the redis server. Result is cached, so done only
one time. | f15579:c0:m8 |
def support_zrangebylex(self): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>self._support_zrangebylex = self.redis_version >= (<NUM_LIT:2>, <NUM_LIT:8>, <NUM_LIT:9>)and hasattr(self.connection, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>self._support_zrangebylex = False<EOL><DEDENT><DEDENT>return self._support_zrangebylex<EOL> | Returns True if zrangebylex is available. Checks are done in the client
library (redis-py) AND the redis server. Result is cached, so done only
one time. | f15579:c0:m9 |
def call_script(self, script_dict, keys=None, args=None): | if keys is None:<EOL><INDENT>keys = []<EOL><DEDENT>if args is None:<EOL><INDENT>args = []<EOL><DEDENT>if '<STR_LIT>' not in script_dict:<EOL><INDENT>script_dict['<STR_LIT>'] = self.connection.register_script(script_dict['<STR_LIT>'])<EOL><DEDENT>return script_dict['<STR_LIT>'](keys=keys, args=args, client=self.connection)<EOL> | Call a redis script with keys and args
The first time we call a script, we register it to speed up later calls.
We expect a dict with a ``lua`` key having the script, and the dict will be
updated with a ``script_object`` key, with the content returned by the
the redis-py ``register_script`` command.
Parameters
----------
script_dict: dict
A dict with a ``lua`` entry containing the lua code. A new key, ``script_object``
will be added after that.
keys: list of str
List of the keys that will be read/updated by the lua script
args: list of str
List of all the args expected by the script.
Returns
-------
Anything that will be returned by the script | f15579:c0:m10 |
def scan_keys(self, match=None, count=None): | cursor = <NUM_LIT:0><EOL>while True:<EOL><INDENT>cursor, keys = self.connection.scan(cursor, match=match, count=count)<EOL>for key in keys:<EOL><INDENT>yield key<EOL><DEDENT>if not cursor or cursor == '<STR_LIT:0>': <EOL><INDENT>break<EOL><DEDENT><DEDENT> | Take a pattern expected by the redis `scan` command and iter on all matching keys
Parameters
----------
match: str
The pattern of keys to look for
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 one. A key can be returned multiple times, it's
related to the way the SCAN command works in redis. | f15579:c0:m11 |
@staticmethod<EOL><INDENT>def zinterstore(*args, **kwargs):<DEDENT> | IntersectTest.last_interstore_call = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': args[<NUM_LIT:1>]<EOL>}<EOL>return IntersectTest.redis_zinterstore(*args, **kwargs)<EOL> | Store arguments and call the real zinterstore command | f15583:c6:m0 |
@staticmethod<EOL><INDENT>def sinterstore(*args, **kwargs):<DEDENT> | IntersectTest.last_interstore_call = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': args[<NUM_LIT:1>]<EOL>}<EOL>return IntersectTest.redis_sinterstore(*args, **kwargs)<EOL> | Store arguments and call the real sinterstore command | f15583:c6:m1 |
def setUp(self): | super(IntersectTest, self).setUp()<EOL>IntersectTest.last_interstore_call = {'<STR_LIT>': None, '<STR_LIT>': [], }<EOL>IntersectTest.redis_zinterstore = self.connection.zinterstore<EOL>self.connection.zinterstore = IntersectTest.zinterstore<EOL>IntersectTest.redis_sinterstore = self.connection.sinterstore<EOL>self.connection.sinterstore = IntersectTest.sinterstore<EOL> | Update the redis zinterstore and sinterstore commands to be able to
store locally arguments for testing them just after the commands are
called. Store the original command to call it after logging, and to
restore it in tearDown. | f15583:c6:m2 |
def tearDown(self): | self.connection.zinterstore = IntersectTest.redis_zinterstore<EOL>self.connection.sinterstore = IntersectTest.redis_sinterstore<EOL>super(IntersectTest, self).tearDown()<EOL> | Restore the zinterstore and sinterstore previously updated in setUp. | f15583:c6:m3 |
def count_commands(self): | return self.connection.info()['<STR_LIT>']<EOL> | Helper method to only count redis commands that work on keys (ie ignore
commands like info...) | f15594:c0:m3 |
def count_keys(self): | return self.connection.dbsize()<EOL> | Helper method to return the number of keys in the test database | f15594:c0:m4 |
def assertNumCommands(self, num=None, func=None, *args, **kwargs): | context = _AssertNumCommandsContext(self, num, *args, **kwargs)<EOL>if func is None:<EOL><INDENT>return context<EOL><DEDENT>context.__enter__()<EOL>try:<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT>except:<EOL><INDENT>context.__exit__(*sys.exc_info())<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>context.__exit__(*sys.exc_info())<EOL><DEDENT> | A context assert, to use with "with":
with self.assertNumCommands(2):
obj.field.set(1)
obj.field.get() | f15594:c0:m5 |
def assertSlicingIsCorrect(self, collection, check_data, check_only_length=False, limit=<NUM_LIT:5>): | <EOL>if check_only_length:<EOL><INDENT>assert len(list(collection)) == len(check_data), '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>assert sorted(collection) == check_data, '<STR_LIT>'<EOL><DEDENT>total, optimized = <NUM_LIT:0>, <NUM_LIT:0><EOL>for start in list(range(-limit, limit+<NUM_LIT:1>)) + [None]:<EOL><INDENT>for stop in list(range(-limit, limit+<NUM_LIT:1>)) + [None]:<EOL><INDENT>for step in range(-limit, limit+<NUM_LIT:1>):<EOL><INDENT>if not step:<EOL><INDENT>continue<EOL><DEDENT>with self.subTest(Start=start, Stop=stop, step=step):<EOL><INDENT>total += <NUM_LIT:1><EOL>result = collection[start:stop:step]<EOL>expected = check_data[start:stop:step]<EOL>if check_only_length:<EOL><INDENT>result = len(result)<EOL>expected = len(expected)<EOL><DEDENT>self.assertEqual(<EOL>result,<EOL>expected,<EOL>'<STR_LIT>' % (<EOL>'<STR_LIT>' if start is None else start,<EOL>'<STR_LIT>' if stop is None else stop,<EOL>'<STR_LIT>' if step is None else step,<EOL>)<EOL>)<EOL>if collection._optimized_slicing:<EOL><INDENT>optimized += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>self.assertGreaterEqual(optimized * <NUM_LIT> / total, <NUM_LIT>,<EOL>"<STR_LIT>")<EOL> | Test a wide range of slicing of the given collection, compared to a python list
Parameters
----------
collection: Collection
The collection to test. Should not have been sliced yet
check_data: list
The python list containing the same values as the limpyd collection.
The result of slicing the collection will be compared to the result of slicing
this list
check_only_length: bool
Default to ``False``. When ``True``, only the length of the slicing of the collection
is comparedc to the slicing of the python list. To be used only when resulting content
cannot be assured (for unsorted collections)
limit: int
Default to ``5``, it's the boundary of the slicing ranges that will be tested.
``5`` means will use all values from ``-5`` to ``5`` for each of the three parts
of the slicing. | f15594:c0:m6 |
@staticmethod<EOL><INDENT>def ping(name):<DEDENT> | LimpydBaseTest.database.connection.publish(name, <NUM_LIT:1>)<EOL> | Send a ping to the given channel name. It's a pubsub publish, used to
communicate within threads. Use wait_for_ping below to receive pings
and call a callback. | f15595:c2:m0 |
@staticmethod<EOL><INDENT>def wait_for_ping(names, callback=None):<DEDENT> | pubsub = LimpydBaseTest.database.connection.pubsub()<EOL>pubsub.subscribe(names)<EOL>for message in pubsub.listen():<EOL><INDENT>if message['<STR_LIT:type>'] == '<STR_LIT:message>':<EOL><INDENT>if message['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>pubsub.unsubscribe(names)<EOL>continue<EOL><DEDENT>pubsub.unsubscribe(message['<STR_LIT>'])<EOL>if callback:<EOL><INDENT>callback(message['<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT> | When a ping (see above) with a name in the given names is received, the
callback is executed. We also stop listening for pings with the received
name. As waiting is a blocking process (using redis pubsub subscribe),
it can be used to call a callback or simply to wait for a ping to
continue execution. | f15595:c2:m1 |
def crypt(password, cost=<NUM_LIT:2>): | salt = _generate_salt(cost)<EOL>hashed = pbkdf2.pbkdf2_hex(password, salt, cost * <NUM_LIT>)<EOL>return "<STR_LIT>" + str(cost) + "<STR_LIT:$>" + salt.decode("<STR_LIT:utf-8>") + "<STR_LIT:$>" + hashed<EOL> | Hash a password
result sample:
$pbkdf2-256-1$8$FRakfnkgpMjnqs1Xxgjiwgycdf68be9b06451039cc\
0f7075ec1c369fa36f055b1705ec7a
The returned string is broken down into
- The algorithm and version used
- The cost factor, number of iterations over the hash
- The salt
- The password | f15601:m0 |
def verify(password, hash): | _, algorithm, cost, salt, password_hash = hash.split("<STR_LIT:$>")<EOL>password = pbkdf2.pbkdf2_hex(password, salt, int(cost) * <NUM_LIT>)<EOL>return _safe_str_cmp(password, password_hash)<EOL> | Verify a password against a passed hash | f15601:m1 |
def _safe_str_cmp(a, b): | if len(a) != len(b):<EOL><INDENT>return False<EOL><DEDENT>rv = <NUM_LIT:0><EOL>for x, y in zip(a, b):<EOL><INDENT>rv |= ord(x) ^ ord(y)<EOL><DEDENT>return rv == <NUM_LIT:0><EOL> | Internal function to efficiently iterate over the hashes
Regular string compare will bail at the earliest opportunity
which allows timing attacks | f15601:m2 |
def pbkdf2_hex(data, salt, iterations=<NUM_LIT:1000>, keylen=<NUM_LIT>, hashfunc=None): | return hexlify_(pbkdf2_bin(data, salt, iterations, keylen, hashfunc))<EOL> | Like :func:`pbkdf2_bin` but returns a hex encoded string. | f15602:m3 |
def pbkdf2_bin(data, salt, iterations=<NUM_LIT:1000>, keylen=<NUM_LIT>, hashfunc=None): | hashfunc = hashfunc or hashlib.sha1<EOL>mac = hmac.new(bytes_(data), None, hashfunc)<EOL>def _pseudorandom(x, mac=mac):<EOL><INDENT>h = mac.copy()<EOL>h.update(bytes_(x))<EOL>if not PY2:<EOL><INDENT>return [x for x in h.digest()]<EOL><DEDENT>else:<EOL><INDENT>return map(ord, h.digest())<EOL><DEDENT><DEDENT>buf = []<EOL>for block in range_(<NUM_LIT:1>, -(-keylen // mac.digest_size) + <NUM_LIT:1>):<EOL><INDENT>rv = u = _pseudorandom(bytes_(salt) + _pack_int(block))<EOL>for i in range_(iterations - <NUM_LIT:1>):<EOL><INDENT>if not PY2:<EOL><INDENT>u = _pseudorandom(bytes(u))<EOL><DEDENT>else:<EOL><INDENT>u = _pseudorandom('<STR_LIT>'.join(map(chr, u)))<EOL><DEDENT>rv = starmap(xor, zip(rv, u))<EOL><DEDENT>buf.extend(rv)<EOL><DEDENT>if not PY2:<EOL><INDENT>return bytes(buf)[:keylen]<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'.join(map(chr, buf))[:keylen]<EOL><DEDENT> | Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided. | f15602:m4 |
@classmethod<EOL><INDENT>def configure_client(cls, host: str = '<STR_LIT:localhost>', port: int = <NUM_LIT>, **client_args):<DEDENT> | assert check_argument_types()<EOL>client = Client(host, port, **client_args)<EOL>return client<EOL> | Configure a Memcached client.
:param host: host name or ip address to connect to
:param port: port number to connect to
:param client_args: extra keyword arguments passed to :class:`aiomcache.Client` | f15606:c0:m1 |
def create_app(): | app = Flask(__name__)<EOL>exceptions = AddExceptions()<EOL>exceptions.init_app(app)<EOL>return app<EOL> | Create a Flask app for context. | f15610:m0 |
def setUp(self): | self.app = create_app()<EOL>self.ctx = self.app.app_context()<EOL>self.ctx.push()<EOL> | Set up tests. | f15610:c0:m0 |
def tearDown(self): | self.ctx.pop()<EOL> | Tear down tests. | f15610:c0:m1 |
def exception(message): | def decorator(method):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(method)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if self.messages:<EOL><INDENT>kwargs['<STR_LIT:message>'] = args[<NUM_LIT:0>] if args else kwargs.get('<STR_LIT:message>', message)<EOL><DEDENT>else:<EOL><INDENT>kwargs['<STR_LIT:message>'] = None<EOL><DEDENT>kwargs['<STR_LIT>'] = self.prefix<EOL>kwargs['<STR_LIT>'] = self.statsd<EOL>return method(self, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | Exception method convenience wrapper. | f15612:m0 |
def to_dict(self): | val = dict(self.payload or ())<EOL>if self.message:<EOL><INDENT>val['<STR_LIT:message>'] = self.message<EOL><DEDENT>return val<EOL> | Convert Exception class to a Python dictionary. | f15612:c0:m1 |
def init_app(self, app, config=None, statsd=None): | if config is not None:<EOL><INDENT>self.config = config<EOL><DEDENT>elif self.config is None:<EOL><INDENT>self.config = app.config<EOL><DEDENT>self.messages = self.config.get('<STR_LIT>', True)<EOL>self.prefix = self.config.get('<STR_LIT>', DEFAULT_PREFIX)<EOL>self.statsd = statsd<EOL> | Init Flask Extension. | f15612:c10:m1 |
@exception('<STR_LIT>')<EOL><INDENT>def bad_request(self, *_, **kwargs):<DEDENT> | return BadRequest(**kwargs)<EOL> | Return an Exception to use when you want to return a 400. | f15612:c10:m2 |
@exception('<STR_LIT>')<EOL><INDENT>def unauthorized(self, *_, **kwargs):<DEDENT> | return Unauthorized(**kwargs)<EOL> | Return an Exception to use when you want to return a 401. | f15612:c10:m3 |
@exception('<STR_LIT>')<EOL><INDENT>def forbidden(self, *_, **kwargs):<DEDENT> | return Forbidden(**kwargs)<EOL> | Return an Exception to use when you want to return a 403. | f15612:c10:m4 |
@exception('<STR_LIT>')<EOL><INDENT>def not_found(self, *_, **kwargs):<DEDENT> | return NotFound(**kwargs)<EOL> | Return an Exception to use when you want to return a 404. | f15612:c10:m5 |
@exception('<STR_LIT>')<EOL><INDENT>def conflict(self, *_, **kwargs):<DEDENT> | return Conflict(**kwargs)<EOL> | Return an Exception to use when you want to return a 409. | f15612:c10:m6 |
@exception('<STR_LIT>')<EOL><INDENT>def gone(self, *_, **kwargs):<DEDENT> | return Gone(**kwargs)<EOL> | Return an Exception to use when you want to return a 410. | f15612:c10:m7 |
@exception('<STR_LIT>')<EOL><INDENT>def unsupported_media(self, *_, **kwargs):<DEDENT> | return UnsupportedMedia(**kwargs)<EOL> | Return an Exception to use when you want to return a 415. | f15612:c10:m8 |
@exception('<STR_LIT>')<EOL><INDENT>def unprocessable_entity(self, *_, **kwargs):<DEDENT> | return UnprocessableEntity(**kwargs)<EOL> | Return an Exception to use when you want to return a 422. | f15612:c10:m9 |
@exception('<STR_LIT>')<EOL><INDENT>def failed_dependency(self, *_, **kwargs):<DEDENT> | return FailedDependency(**kwargs)<EOL> | Return an Exception to use when you want to return a 424. | f15612:c10:m10 |
def format(self, *args, **kwargs): | custom = kwargs['<STR_LIT>'].replace('<STR_LIT:U+0020>', '<STR_LIT>').upper()<EOL>return super(CustomFormatting, self).format(*args, custom=custom, **kwargs)<EOL> | Override default format method. | f15615:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.