Syntactic Sugar¶
Various minor things to make life easier, prettier, more concise and/or less error prone.
Command Function Decorator¶
The @redgrease.command
decorator can be put on functions to immediately turn them into CommandReader GearFunctions.
The decorator takes all the same parameters as the CommandReader.register()
, but the trigger
argument is optional, and the name of the function is used as default.
The decorator also takes a boolean keyword argument replace
which indicates what should be done if a function with the same trigger has already been registered, as follows:
None
- Default - Aredgrease.exceptions.DuplicateTriggerError
error is raised.True
- The registered function is replaced.False
- Nothing. No error is raised, but the existing registered function remains.
The decorator also takes the keyword on
, which if provided with a Redis Gears client connection, attempts to register the function as a command reader on the server.
The GearFunction can be triggered by simply locally calling the decorated function, just as if it was a local function. Under the hood, however, this will send the trigger and any passed arguments to the server, which in turn runs the registered CommandReader function on the Redis shards, and then retuns the function results to the caller.
2
3import redgrease
4
5# Bind / register the function on some Redis instance.
6r = redgrease.RedisGears()
7
8
9# CommandReader Decorator
10# The `command` decorator tunrs the function to a CommandReader,
11# registerered on the Redis Gears sever if using the `on` argument
12@redgrease.command(on=r, requirements=["requests"], replace=False)
13def cache_get(url):
14 import requests
15
16 # Check if the url is already in the cache,
17 # And if so, simply return the cached result.
18 if redgrease.cmd.exists(url):
19 return bytes(redgrease.cmd.get(url))
20
21 # Otherwise fetch the url.
22 response = requests.get(url)
23
24 # Return nothing if request fails
25 if response.status_code != 200:
26 return bytes()
27
28 # If ok, set the cache data and return.
29 response_data = bytes(response.content)
30 redgrease.cmd.set(url, response_data)
31
32 return response_data
33
34
Note
The on
argument is actually optional, but in that case the decorated function cannot be called locally as described above.
Instead the function name becomes a “Closed” CommandReader GearFunction, which can be turned into a function as per above again, by calling the on()
method:
import redgrease
# ``on`` argument **not** provided => ``foo`` becomes a Closed GearFunction
@redgrease.command()
def foo(arg1, arg2):
redgrease.cmd.log(f"Pretending to do something with {arg1} and {arg2}")
r = redgrease.RedisGears()
# Call ``on`` on foo with a Gears client
# => result is a local triggering function
do_foo = foo.on(r)
# Call / trigger the function
do_foo("this", "that")
- redgrease.command(trigger: Optional[str] = None, prefix: str = '*', collect: bool = True, mode: str = 'async', onRegistered: Optional[Callable[[], None]] = None, **kargs) Callable[[Callable], redgrease.gears.ClosedGearFunction] [source]¶
Decorator for creation of CommandReader + Trigger GearFunctions
- Parameters
trigger (str, optional) – The trigger string Will be a the function name if not specified (None). The special value … (Ellipsis) wil give the function a unique trigger. Defaults to None
prefix (str, optional) – Register prefix. Same as for the register operation. Defaults to “*”.
collect (bool, optional) – Add a collect’ operation to the end of the function. Same as for the `register operation. Defaults to True.
mode (str, optional) – The execution mode of the triggered function. Same as for the register operation. Defaults to redgrease.sugar.TriggerMode.Async.
onRegistered (
redgrease.typing.Registrator
, optional) – A function callback thats called on each shard upon function registration. It is a good place to initialize non-serializeable objects such as network connections. Same as for the register operation. Defaults to None.
- Returns
A ClosedGearFunction generator.
- Return type
Callable[[Callable], ClosedGearFunction]
Keywords¶
Moderately useful symbols that can be used instead of strings for various RedisGears Keywords.
Reader Types¶
- ReaderType.KeysReader = 'KeysReader'¶
KeysReader
- ReaderType.KeysOnlyReader = 'KeysOnlyReader'¶
KeysOnlyReader
- ReaderType.StreamReader = 'StreamReader'¶
StreamReader
- ReaderType.PythonReader = 'PythonReader'¶
PythonReader
- ReaderType.ShardsIDReader = 'ShardsIDReader'¶
ShardsIDReader
- ReaderType.CommandReader = 'CommandReader'¶
CommandReader
Example:
from redgrease import GearsBuilder, ReaderType
gb = GearsBuilder(ReaderType.KeysReader).run()
Trigger Modes¶
- TriggerMode.Async = 'async'¶
Async
- TriggerMode.AsyncLocal = 'async_local'¶
AsyncLocal
- TriggerMode.Sync = 'sync'¶
Sync
Example:
from redgrease import GearsBuilder, KeysReader, TriggerMode
fun = KeysReader().register(mode=TriggerMode.AsyncLocal)
Key types¶
- KeyType.String = 'string'¶
String
- KeyType.Hash = 'hash'¶
Hash
- KeyType.List = 'list'¶
List
- KeyType.Set = 'set'¶
Set
- KeyType.ZSet = 'zset'¶
ZSet
- KeyType.Stream = 'stream'¶
Stream
- KeyType.Module = 'module'¶
Module
Example:
from redgrease import KeysReader, KeyType
fun = KeysReader().register(keyTypes=[KeyType.List, KeyType.Set, KeyType.ZSet])
Failure Policies¶
- FailurePolicy.Continue = 'continue'¶
Continue
- FailurePolicy.Abort = 'abort'¶
Abort
- FailurePolicy.Retry = 'retry'¶
Retry
Example:
from redgrease import StreamReader, FailurePolicy
fun = StreamReader().register(onFailedPolicy=FailurePolicy.Abort)
Log Levels¶
- LogLevel.Debug = 'debug'¶
Debug
- LogLevel.Verbose = 'verbose'¶
Verbose
- LogLevel.Notice = 'notice'¶
Notice
- LogLevel.Warning = 'warning'¶
Warning
Example:
from redgrease import KeysOnlyReader, LogLevel
fun = KeysOnlyReader().map(lambda k: log(f"Processing key: {k}", level=LogLevel.Debug).run()