| |
- builtins.Exception(builtins.BaseException)
-
- InvalidModelException
- builtins.object
-
- IndexedRedisHelper
-
- IndexedRedisDelete
- IndexedRedisQuery
- IndexedRedisSave
- IndexedRedisModel
- builtins.str(builtins.object)
-
- IndexedRedis.fields.IRField
-
- IndexedRedis.fields.chain.IRFieldChain
class IRField(builtins.str) |
|
IRField - An advanced field
@param name <str> - The field name
@param valueType <None/type> - The type to use for the value of this field. Default is str (str/unicode will both be unicode). If on python3 and bytes are passed, will be decoded to bytes using default encoding.
Using None, the raw data will be used (bytes) on retrieval and for storage.
Can be a basic type (like int). Use BINARY_FIELDS array on the model to have value be "bytes"
If a type is defined other than default/str/bytes/None , an empty value (empty string in Redis) will be assigned to the IRNullType instance provided in this module, irNull.
irNull does not equal anything except irNull (or another IRNullType). Use this to check if a value has been assigned for other types.
BE VERY CAREFUL ABOUT USING "float" as a type! It is an inprecise field and can vary from system to system. Instead of using a float,
consider using fields.IRFixedPointField, which is indexable. |
|
- Method resolution order:
- IRField
- builtins.str
- builtins.object
Methods defined here:
- __init__(self, name='', valueType=<class 'str'>)
- convert(self, value)
- convert - Convert the value from storage (string) to the value type.
@return - The converted value, or "irNull" if no value was defined (and field type is not default/string)
- toStorage(self, value)
- toStorage - Convert the value to a string representation for storage.
The default implementation will work here for basic types.
@param value - The value of the item to convert
@return A string value suitable for storing.
Static methods defined here:
- __new__(self, name='', valueType=None)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes defined here:
- CAN_INDEX = False
Methods inherited from builtins.str:
- __add__(self, value, /)
- Return self+value.
- __contains__(self, key, /)
- Return key in self.
- __eq__(self, value, /)
- Return self==value.
- __format__(...)
- S.__format__(format_spec) -> str
Return a formatted version of S as described by format_spec.
- __ge__(self, value, /)
- Return self>=value.
- __getattribute__(self, name, /)
- Return getattr(self, name).
- __getitem__(self, key, /)
- Return self[key].
- __getnewargs__(...)
- __gt__(self, value, /)
- Return self>value.
- __hash__(self, /)
- Return hash(self).
- __iter__(self, /)
- Implement iter(self).
- __le__(self, value, /)
- Return self<=value.
- __len__(self, /)
- Return len(self).
- __lt__(self, value, /)
- Return self<value.
- __mod__(self, value, /)
- Return self%value.
- __mul__(self, value, /)
- Return self*value.n
- __ne__(self, value, /)
- Return self!=value.
- __repr__(self, /)
- Return repr(self).
- __rmod__(self, value, /)
- Return value%self.
- __rmul__(self, value, /)
- Return self*value.
- __sizeof__(...)
- S.__sizeof__() -> size of S in memory, in bytes
- __str__(self, /)
- Return str(self).
- capitalize(...)
- S.capitalize() -> str
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
- casefold(...)
- S.casefold() -> str
Return a version of S suitable for caseless comparisons.
- center(...)
- S.center(width[, fillchar]) -> str
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
- count(...)
- S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
- encode(...)
- S.encode(encoding='utf-8', errors='strict') -> bytes
Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(...)
- S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
- expandtabs(...)
- S.expandtabs(tabsize=8) -> str
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(...)
- S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(...)
- S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
- format_map(...)
- S.format_map(mapping) -> str
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
- index(...)
- S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
- isalnum(...)
- S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
- isalpha(...)
- S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
- isdecimal(...)
- S.isdecimal() -> bool
Return True if there are only decimal characters in S,
False otherwise.
- isdigit(...)
- S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
- isidentifier(...)
- S.isidentifier() -> bool
Return True if S is a valid identifier according
to the language definition.
Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
- islower(...)
- S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
- isnumeric(...)
- S.isnumeric() -> bool
Return True if there are only numeric characters in S,
False otherwise.
- isprintable(...)
- S.isprintable() -> bool
Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
- isspace(...)
- S.isspace() -> bool
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
- istitle(...)
- S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
- isupper(...)
- S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
- join(...)
- S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
- ljust(...)
- S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
- lower(...)
- S.lower() -> str
Return a copy of the string S converted to lowercase.
- lstrip(...)
- S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- partition(...)
- S.partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
- replace(...)
- S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
- rfind(...)
- S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(...)
- S.rindex(sub[, start[, end]]) -> int
Like S.rfind() but raise ValueError when the substring is not found.
- rjust(...)
- S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
- rpartition(...)
- S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
- rsplit(...)
- S.rsplit(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
- rstrip(...)
- S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(...)
- S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
- splitlines(...)
- S.splitlines([keepends]) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
- startswith(...)
- S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
- strip(...)
- S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase(...)
- S.swapcase() -> str
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
- title(...)
- S.title() -> str
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
- translate(...)
- S.translate(table) -> str
Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
- upper(...)
- S.upper() -> str
Return a copy of S converted to uppercase.
- zfill(...)
- S.zfill(width) -> str
Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
Static methods inherited from builtins.str:
- maketrans(x, y=None, z=None, /)
- Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
|
class IRFieldChain(IndexedRedis.fields.IRField) |
| |
- Method resolution order:
- IRFieldChain
- IndexedRedis.fields.IRField
- builtins.str
- builtins.object
Methods defined here:
- __init__(self, name, chainedFields)
- convert(self, value)
- convert - Convert the value from storage (string) to the value type.
@return - The converted value, or "irNull" if no value was defined (and field type is not default/string)
- toStorage(self, value)
- toStorage - Convert the value to a string representation for storage.
The default implementation will work here for basic types.
@param value - The value of the item to convert
@return A string value suitable for storing.
Static methods defined here:
- __new__(self, name, chainedFields=None)
Data and other attributes defined here:
- CAN_INDEX = False
Data descriptors inherited from IndexedRedis.fields.IRField:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Methods inherited from builtins.str:
- __add__(self, value, /)
- Return self+value.
- __contains__(self, key, /)
- Return key in self.
- __eq__(self, value, /)
- Return self==value.
- __format__(...)
- S.__format__(format_spec) -> str
Return a formatted version of S as described by format_spec.
- __ge__(self, value, /)
- Return self>=value.
- __getattribute__(self, name, /)
- Return getattr(self, name).
- __getitem__(self, key, /)
- Return self[key].
- __getnewargs__(...)
- __gt__(self, value, /)
- Return self>value.
- __hash__(self, /)
- Return hash(self).
- __iter__(self, /)
- Implement iter(self).
- __le__(self, value, /)
- Return self<=value.
- __len__(self, /)
- Return len(self).
- __lt__(self, value, /)
- Return self<value.
- __mod__(self, value, /)
- Return self%value.
- __mul__(self, value, /)
- Return self*value.n
- __ne__(self, value, /)
- Return self!=value.
- __repr__(self, /)
- Return repr(self).
- __rmod__(self, value, /)
- Return value%self.
- __rmul__(self, value, /)
- Return self*value.
- __sizeof__(...)
- S.__sizeof__() -> size of S in memory, in bytes
- __str__(self, /)
- Return str(self).
- capitalize(...)
- S.capitalize() -> str
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
- casefold(...)
- S.casefold() -> str
Return a version of S suitable for caseless comparisons.
- center(...)
- S.center(width[, fillchar]) -> str
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
- count(...)
- S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
- encode(...)
- S.encode(encoding='utf-8', errors='strict') -> bytes
Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(...)
- S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
- expandtabs(...)
- S.expandtabs(tabsize=8) -> str
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(...)
- S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(...)
- S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
- format_map(...)
- S.format_map(mapping) -> str
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
- index(...)
- S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
- isalnum(...)
- S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
- isalpha(...)
- S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
- isdecimal(...)
- S.isdecimal() -> bool
Return True if there are only decimal characters in S,
False otherwise.
- isdigit(...)
- S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
- isidentifier(...)
- S.isidentifier() -> bool
Return True if S is a valid identifier according
to the language definition.
Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
- islower(...)
- S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
- isnumeric(...)
- S.isnumeric() -> bool
Return True if there are only numeric characters in S,
False otherwise.
- isprintable(...)
- S.isprintable() -> bool
Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
- isspace(...)
- S.isspace() -> bool
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
- istitle(...)
- S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
- isupper(...)
- S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
- join(...)
- S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
- ljust(...)
- S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
- lower(...)
- S.lower() -> str
Return a copy of the string S converted to lowercase.
- lstrip(...)
- S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- partition(...)
- S.partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
- replace(...)
- S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
- rfind(...)
- S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(...)
- S.rindex(sub[, start[, end]]) -> int
Like S.rfind() but raise ValueError when the substring is not found.
- rjust(...)
- S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
- rpartition(...)
- S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
- rsplit(...)
- S.rsplit(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
- rstrip(...)
- S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(...)
- S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
- splitlines(...)
- S.splitlines([keepends]) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
- startswith(...)
- S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
- strip(...)
- S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase(...)
- S.swapcase() -> str
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
- title(...)
- S.title() -> str
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
- translate(...)
- S.translate(table) -> str
Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
- upper(...)
- S.upper() -> str
Return a copy of S converted to uppercase.
- zfill(...)
- S.zfill(width) -> str
Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
Static methods inherited from builtins.str:
- maketrans(x, y=None, z=None, /)
- Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
|
class IndexedRedisDelete(IndexedRedisHelper) |
|
IndexedRedisDelete - Used for removing objects. Called when Model.delete is used.
Except for advanced usage, this is probably for internal only. |
|
- Method resolution order:
- IndexedRedisDelete
- IndexedRedisHelper
- builtins.object
Methods defined here:
- deleteByPk(self, pk)
- deleteByPk - Delete object associated with given primary key
- deleteMultiple(self, objs)
- deleteMultiple - Delete multiple objects
@param objs - List of objects
@return - Number of objects deleted
- deleteMultipleByPks(self, pks)
- deleteMultipleByPks - Delete multiple objects given their primary keys
@param pks - List of primary keys
@return - Number of objects deleted
- deleteOne(self, obj, conn=None)
- deleteOne - Delete one object
@param obj - object to delete
@param conn - Connection to reuse, or None
@return - number of items deleted (0 or 1)
- destroyModel(self)
- destroyModel - Destroy everything related to this model in one swoop.
Same effect as Model.reset([]) - Except slightly more efficient.
This function is called if you do Model.objects.delete() with no filters set.
@return - Number of keys deleted. Note, this is NOT number of models deleted, but total keys.
Methods inherited from IndexedRedisHelper:
- __init__(self, mdl)
- Internal constructor
@param mdl - IndexedRedisModel implementer
Data descriptors inherited from IndexedRedisHelper:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class IndexedRedisModel(builtins.object) |
|
IndexedRedisModel - This is the model you should extend.
**Required Fields:**
*FIELDS* - REQUIRED. a list of strings which name the fields that can be used for storage. Can also be IRField or an implementing type (see AdvancedFields below)
Example: ['Name', 'Description', 'Model', 'Price']
*INDEXED_FIELDS* - a list of strings containing the names of fields that will be indexed. Can only filter on indexed fields. Adds insert/delete time. Contents must also be in FIELDS.
Example: ['Name', 'Model']
*BASE64_FIELDS* - A list of strings which name the fields that will be stored as base64-encoded strings. All entries must also be present in FIELDS.
Example: ['data', 'blob']
*BINARY_FIELDS* - A list of strings which name the fields that will be stored as unencoded binary data. All entries must also be present in FIELDS.
*KEY_NAME* - REQUIRED. A unique name name that represents this model. Think of it like a table name.
Example: 'Items'
*REDIS_CONNECTION_PARAMS* - provides the arguments to pass into "redis.Redis", to construct a redis object.
Usage
-----
Usage is very similar to Django or Flask.
**Query:**
Calling .filter or .filterInline builds a query/filter set. Use one of the *Fetch* methods described below to execute a query.
objects = SomeModel.objects.filter(param1=val).filter(param2=val).all()
**Save:**
obj = SomeModel(field1='value', field2='value')
obj.save()
**Delete Using Filters:**
SomeModel.objects.filter(name='Bad Man').delete()
**Delete Individual Objects:**
obj.delete()
**Atomic Dataset Replacement:**
There is also a powerful method called "reset" which will **atomically** replace all elements belonging to a model. This is useful for cache-replacement, etc.
lst = [SomeModel(...), SomeModel(..)]
SomeModel.reset(lst)
For example, you could have a SQL backend and a cron job that does complex queries (or just fetches the same models) and does an atomic replace every 5 minutes to get massive performance boosts in your application.
Filter objects by SomeModel.objects.filter(key=val, key2=val2) and get objects with .all
Example: SomeModel.objects.filter(name='Tim', colour='purple').filter(number=5).all()
**Fetch Functions**:
Building filtersets do not actually fetch any data until one of these are called (see API for a complete list). All of these functions act on current filterset.
Example: matchingObjects = SomeModel.objects.filter(...).all()
all - Return all objects matching this filter
allOnlyFields - Takes a list of fields and only fetches those fields, using current filterset
delete - Delete objects matching this filter
count - Get the count of objects matching this filter
first - Get the oldest record with current filters
last - Get the newest record with current filters
random - Get a random element with current filters
getPrimaryKeys - Gets primary keys associated with current filters
**Filter Functions**
These functions add filters to the current set. "filter" returns a copy, "filterInline" acts on that object.
filter - Add additional filters, returning a copy of the filter object (moreFiltered = filtered.filter(key2=val2))
filterInline - Add additional filters to current filter object.
**Global Fetch functions**
These functions are available on SomeModel.objects and don't use any filters (they get specific objects):
get - Get a single object by pk
getMultiple - Get multiple objects by a list of pks
**Model Functions**
Actual objects contain methods including:
save - Save this object (create if not exist, otherwise update)
delete - Delete this object
getUpdatedFields - See changes since last fetch
Advanced Fields
---------------
IndexedRedis since version 4.0 allows you to pass elements of type IRField (extends str) in the FIELDS element.
Doing so allows you to specify certain properties about the field.
Example:
FIELDS = [ 'name', IRField('age', valueType=int), 'birthday' ]
**Field Name**
The first argument is the string of the field name.
**Type**
You can have a value automatically cast to a certain type (which saves a step if you need to filter further through the QueryableList results, like age__gt=15)
by passing that type as "valueType". (e.x. IRField('age', valueType=int))
If you use "bool", the values 0 and case insensitive string 'false' will result in False, and 1 or 'true' will result in True.
Be careful using floats, different hosts will have different floating point representations for the same value. Don't expect
floats to work cross-platform. Use a fixed point number as the string type ( like myFixedPoint = '%2.5f' %( 10.12345 ) )
** Null Values **
For any type except strings (including the default type, string), a null value is assigned irNull (of type IRNullType).
irNull does not equal empty string, or anything except another irNull. This is to destinguish say, no int assigned vs int(0)
You can check a typed field against the "irNull" variable found in the IndexedRedis or IndexedRedis.fields.
from IndexedRedis import irNull
..
e.x. notDangerFive = myResults.filter(dangerLevel__ne=irNull).filter(dangerLevel__ne=5)
or even
notDangerFive = MyModel.objects.filter(dangerLevel__ne=irNull).filter(dangerLevel__ne=5).all()
Encodings
---------
IndexedRedis will use by default your system default encoding (sys.getdefaultencoding), unless it is ascii (python2) in which case it will default to utf-8.
You may change this via IndexedRedis.setDefaultIREncoding |
|
Methods defined here:
- __getstate__(self)
- pickle uses this
- __init__(self, *args, **kwargs)
- __init__ - Set the values on this object. MAKE SURE YOU CALL THE SUPER HERE, or else things will not work.
- __repr__(self)
- __repr__ - Returns a string of the constructor/params to recreate this object.
Example: objCopy = eval(repr(obj))
@return - String of python init call to recreate this object
- __setstate__(self, stateDict)
- pickle uses this
- __str__(self)
- __str__ - Returns a string representation of this object's state.
See implementation.
@return <str>-
Some samples:
(Pdb) str(z)
'<Song obj _id=24 at 0x7f3c6a3a4490>'
(Pdb) z.artist = 'New Artist'
(Pdb) str(z)
'<Song obj _id=24 (Unsaved Changes) at 0x7f3c6a3a4490>'
- asDict(self, includeMeta=False, forStorage=False)
- toDict / asDict - Get a dictionary representation of this model.
@param includeMeta - Include metadata in return. For now, this is only pk stored as "_id"
@param convertValueTypes <bool> - default True. If False, fields with fieldValue defined will be converted to that type.
Use True when saving, etc, as native type is always either str or bytes.
@return - Dictionary reprensetation of this object and all fields
- copy(self, copyPrimaryKey=False)
- copy - Copies this object.
@param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis.
If False, only the data is copied, and nothing is saved.
- delete(self)
- delete - Delete this object
- getPk(self)
- getPk - Gets the internal primary key associated with this object
- getUpdatedFields(self)
- getUpdatedFields - See changed fields.
@return - a dictionary of fieldName : tuple(old, new).
fieldName may be a string or may implement IRField (which implements string, and can be used just like a string)
- hasUnsavedChanges(self)
- hasUnsavedChanges - Check if any unsaved changes are present in this model, or if it has never been saved.
@return <bool> - True if any fields have changed since last fetch, or if never saved. Otherwise, False
- objects
- reload(self)
- reload - Reload this object from the database, overriding any local changes and merging in any updates.
@raises KeyError - if this object has not been saved (no primary key)
@return - Dict with the keys that were updated. Key is field name that was updated,
and value is tuple of (old value, new value).
- save(self)
- save - Save this object
- saveToExternal(self, redisCon)
- saveToExternal - Saves this object to a different Redis than that specified by REDIS_CONNECTION_PARAMS on this model.
@param redisCon <dict/redis.Redis> - Either a dict of connection params, a la REDIS_CONNECTION_PARAMS, or an existing Redis connection.
If you are doing a lot of bulk copies, it is recommended that you create a Redis connection and pass it in rather than establish a new
connection with each call.
@note - You will generate a new primary key relative to the external Redis environment. If you need to reference a "shared" primary key, it is better
to use an indexed field than the internal pk.
- toDict = asDict(self, includeMeta=False, forStorage=False)
Class methods defined here:
- connect(redisConnectionParams) from builtins.type
- connect - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model.
@param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS.
@return - A class that can be used in all the same ways as the existing IndexedRedisModel, but that connects to a different instance.
- reset(newValues) from builtins.type
- validateModel() from builtins.type
- validateModel - Class method that validates a given model is implemented correctly. Will only be validated once, on first model instantiation.
@param model - Implicit of own class
@return - True
@raises - InvalidModelException if there is a problem with the model, and the message contains relevant information.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes defined here:
- BASE64_FIELDS = []
- BINARY_FIELDS = []
- FIELDS = []
- INDEXED_FIELDS = []
- KEY_NAME = None
- REDIS_CONNECTION_PARAMS = {}
- deleter = <IndexedRedis.IndexedRedisDelete object>
- saver = <IndexedRedis.IndexedRedisSave object>
|
class IndexedRedisQuery(IndexedRedisHelper) |
|
IndexedRedisQuery - The query object. This is the return of "Model.objects" and "Model.objects.filter" |
|
- Method resolution order:
- IndexedRedisQuery
- IndexedRedisHelper
- builtins.object
Methods defined here:
- __init__(self, *args, **kwargs)
- all(self)
- all - Get the underlying objects which match the filter criteria.
Example: objs = Model.objects.filter(field1='value', field2='value2').all()
@return - Objects of the Model instance associated with this query.
- allByAge(self)
- allByAge - Get the underlying objects which match the filter criteria, ordered oldest -> newest
If you are doing a queue or just need the head/tail, consider .first() and .last() instead.
@return - Objects of the Model instance associated with this query, sorted oldest->newest
- allOnlyFields(self, fields)
- allOnlyFields - Get the objects which match the filter criteria, only fetching given fields.
@param fields - List of fields to fetch
@return - Partial objects with only the given fields fetched
- allOnlyIndexedFields(self)
- allOnlyIndexedFields - Get the objects which match the filter criteria, only fetching indexed fields.
@return - Partial objects with only the indexed fields fetched
- count(self)
- count - gets the number of records matching the filter criteria
Example:
theCount = Model.objects.filter(field1='value').count()
- delete(self)
- delete - Deletes all entries matching the filter criteria
- exists(self, pk)
- exists - Tests whether a record holding the given primary key exists.
@param pk - Primary key (see getPk method)
Example usage: Waiting for an object to be deleted without fetching the object or running a filter.
This is a very cheap operation.
@return <bool> - True if object with given pk exists, otherwise False
- filter(self, **kwargs)
- filter - Add filters based on INDEXED_FIELDS having or not having a value.
Note, no objects are actually fetched until .all() is called
Use the field name [ model.objects.filter(some_field='value')] to filter on items containing that value.
Use the field name suffxed with '__ne' for a negation filter [ model.objects.filter(some_field__ne='value') ]
Example:
query = Model.objects.filter(field1='value', field2='othervalue')
objs1 = query.filter(something__ne='value').all()
objs2 = query.filter(something__ne=7).all()
@returns - A copy of this object, with the additional filters. If you want to work inline on this object instead, use the filterInline method.
- filterInline(self, **kwargs)
- filterInline - @see IndexedRedisQuery.filter. This is the same as filter, but works inline on this object instead of creating a copy.
Use this is you do not need to retain the previous filter object.
- first(self)
- First - Returns the oldest record (lowerst primary key) with current filters.
This makes an efficient queue, as it only fetches a single object.
@return - Instance of Model object, or None if no items match current filters
- get(self, pk)
- get - Get a single value with the internal primary key.
@param pk - internal primary key (can be found via .getPk() on an item)
- getMultiple(self, pks)
- getMultiple - Gets multiple objects with a single atomic operation
@param pks - list of internal keys
- getMultipleOnlyFields(self, pks, fields)
- getMultipleOnlyFields - Gets only certain fields from a list of primary keys. For working on entire filter set, see allOnlyFields
pks list<str> - Primary Keys
fields list<str> - List of fields
return - List of partial objects with only fields applied
- getMultipleOnlyIndexedFields(self, pks)
- getMultipleOnlyIndexedFields - Get only the indexed fields on an object. This is the minimum to delete.
@param pks - List of primary keys
@return - List of objects with only indexed fields fetched
- getOnlyFields(self, pk, fields)
- getOnlyFields - Gets only certain fields from a paticular primary key. For working on entire filter set, see allOnlyFields
pk - Primary Key
fields list<str> - List of fields
return - Partial objects with only fields applied
- getOnlyIndexedFields(self, pk)
- getOnlyIndexedFields - Get only the indexed fields on an object. This is the minimum to delete.
@param pk - Primary key
@return - Object with only indexed fields fetched.
- getPrimaryKeys(self, sortByAge=False)
- getPrimaryKeys - Returns all primary keys matching current filterset.
@param sortByAge <bool> - If False, return will be a set and may not be ordered.
If True, return will be a list and is guarenteed to represent objects oldest->newest
@return <set> - A set of all primary keys associated with current filters.
- last(self)
- Last - Returns the newest record (highest primary key) with current filters.
This makes an efficient queue, as it only fetches a single object.
@return - Instance of Model object, or None if no items match current filters
- random(self)
- Random - Returns a random record in current filterset.
@return - Instance of Model object, or None if no items math current filters
- reindex(self)
- reindex - Reindexes the objects matching current filterset. Use this if you add/remove a field to INDEXED_FIELDS
Data descriptors inherited from IndexedRedisHelper:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class IndexedRedisSave(IndexedRedisHelper) |
|
IndexedRedisClass - Class used to save objects. Used with Model.save is called.
Except for advanced usage, this is probably for internal only. |
|
- Method resolution order:
- IndexedRedisSave
- IndexedRedisHelper
- builtins.object
Methods defined here:
- reindex(self, objs, conn=None)
- reindex - Reindexes a given list of objects. Probably you want to do Model.objects.reindex() instead of this directly.
@param objs list<IndexedRedisModel> - List of objects to reindex
@param conn <redis.Redis or None> - Specific Redis connection or None to reuse
- save(self, obj, usePipeline=True, forceID=False, conn=None)
- save - Save an object associated with this model. **Interal Function!!** You probably want to just do object.save() instead of this.
@param obj <IndexedRedisModel or list<IndexedRedisModel> - The object to save, or a list of objects to save
@param usePipeline - Use a pipeline for saving. You should always want this, unless you are calling this function from within an existing pipeline.
@param forceID - if not False, force ID to this. If obj is list, this is also list. Forcing IDs also forces insert. Up to you to ensure ID will not clash.
@param conn - A connection or None
@note - if no ID is specified
@return - List of pks
- saveMultiple(self, objs)
- saveMultiple - Save a list of objects using a pipeline.
@param objs < list<IndexedRedisModel> > - List of objects to save
Methods inherited from IndexedRedisHelper:
- __init__(self, mdl)
- Internal constructor
@param mdl - IndexedRedisModel implementer
Data descriptors inherited from IndexedRedisHelper:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class InvalidModelException(builtins.Exception) |
|
InvalidModelException - Raised if a model fails validation (not valid) |
|
- Method resolution order:
- InvalidModelException
- builtins.Exception
- builtins.BaseException
- builtins.object
Data descriptors defined here:
- __weakref__
- list of weak references to the object (if defined)
Methods inherited from builtins.Exception:
- __init__(self, /, *args, **kwargs)
- Initialize self. See help(type(self)) for accurate signature.
- __new__(*args, **kwargs) from builtins.type
- Create and return a new object. See help(type) for accurate signature.
Methods inherited from builtins.BaseException:
- __delattr__(self, name, /)
- Implement delattr(self, name).
- __getattribute__(self, name, /)
- Return getattr(self, name).
- __reduce__(...)
- __repr__(self, /)
- Return repr(self).
- __setattr__(self, name, value, /)
- Implement setattr(self, name, value).
- __setstate__(...)
- __str__(self, /)
- Return str(self).
- with_traceback(...)
- Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
Data descriptors inherited from builtins.BaseException:
- __cause__
- exception cause
- __context__
- exception context
- __dict__
- __suppress_context__
- __traceback__
- args
| |