Package: redio
RedIO - Redis for TrioA Python 3.7+ module for using Redis database in async programs based on the Trio library.pip install redioThis module is not ready for production use and all APIs are still likely to change. It works with my applications and performs roughly at the same speed as other Redis modules for Python.Normal mode (high level API)importredio,trio# Initialise a connection poolredis=redio.Redis("redis://localhost/")asyncdefmain():some,another=awaitredis().get("somekey").get("anotherkey")print("Got values:",some,another)trio.run(main)Most normalRedis commandsare available and they can either be called in such sequence like above, or if more convenient, using a variable:db=redis()# Get a DB objectdb.get("bar")db.set("bar","value").expire("bar",0.5)# Automatically deleted after 500 msdb.get("bar")old_bar,expire,bar=awaitdbAll commands are queued and sent to server only on the nextawait, improving performance especially if the Redis server is not on localhost, as unnecessary server round-trips are eliminated and often everything fits in a single packet.Responses are returned as a list in the same order as the commands, noting that commands such assetdo not produce any output.Hash keysRedis keys may contain dictionaries with field names and values. RedIOhsetallows specifying fields bykeyword arguments:awaitredis().hset("hashkey",field1=bytes([255,0,255]),field2="text",field3=1.23,)Instead of keyword arguments, adictmay be used. Similarly, values returned byhgetallcome as a dictionary:>>>awaitredis().hgetall("hashkey").autodecode{'field1':b'\xff\x00\xff','field2':'text','field3':1.23,}TransactionsA MULTI/EXEC transaction allows atomic execution without other clients running any commands in between. The following increments keys foo and bar atomically and returns their new values:>>>awaitredis().multi().incr("foo").incr("bar").exec()[1,1]Note: Redis cannot abort and undo an ongoing transaction once it has started. The server will attempt to execute all of the commands, even after errors.One or more WATCH commands may be used prior to transaction to implement optimistic locking usingcheck-and-setwhere the transaction is discarded if any of the watched keys were modified. Usually the operation is attempted again until successful:db=redis()# Inverts the capitalization of foo (sets "DEFAULT value" if foo does not exist)whileTrue:db.watch("foo")foo=awaitdb.get("foo")orb"default VALUE"db.multi()db.set("foo",foo.swapcase())ifawaitdb.exec():breakFalseis returned byexecif the transaction was discarded. Otherwise a list of responses orTrueis returned. In this example a boolean is always returned because the only command within the transaction wassetwhich does not produce any output.Pub/Sub channelsSending messagesMessages are published via normalpublishcommands:awaitredis().publish("channel","message")Receiving messagesReceiving connections can be created by callingpubsubon the connection pool:asyncformessageinredis.pubsub("channel"):print(message)Additional channels may be subscribed bysubscribeandpsubscribecommands
on the PubSub object, and zero or more initial channels may be specified while
creating the object by callingredis.pubsub().By default only messages are received. When subscribing multiple channels on the
same PubSub receiver, it may be useful to receive channel names as well, enabled
by the.with_channelmodifier. As with the standard interface, all commands
and modifiers can be chained or called separately, as they returnself.pubsub=redis.pubsub().strdecode.with_channelpubsub.subscribe("foo","bar")pubsub.psubscribe("chan*")asyncforchannel,messageinpubsub:print(message,"from",channel)Instead ofasync foryou may equivalentlyawait pubsubto receive a single message.Bytes encoding and decodingCommand encodingRedis commands only take bytes and have no other data types. Any non-bytes arguments are automatically encoded (strings, numbers, json):db=redis()db.set("binary",bytes([128,0,255]))db.set("number",10)db.set("jsonkey",dict(foo=123,bar=[1,2,3]))awaitdbResponse decodingKeys such as field names and channel names are always decoded intostrand the decoding modes only affect handling of values (content). Many Redis protocol commands also respond with typed integer, string or list responses which are not affected by this.Three decoding modes are provided for raw byte values. By default, values are not decoded. The other modes are enabled by modifiers.strdecodeand.autodecode, which affectonlythe nextawait. Pub/Sub mode does not reset its decoding settings, so they persist once initially set.Default (no decoding)>>>awaitdb.get("binary").get("number").get("jsonkey")[b"\x80\x00\xFF",b"10",b'{"foo": 123, "bar": [1, 2, 3]}'].strdecode>>>awaitdb.get("binary").get("number").get("jsonkey").strdecode['\udc80\x00\udcff','10','{"foo": 123, "bar": [1, 2, 3]}',]All values are decoded intostrwith invalid UTF-8 sequences replaced by Unicode surrogate values..autodecode>>>awaitdb.get("binary").get("number").get("jsonkey").autodecode[b"\x80\x00\xFF",10,{'foo':123,'bar':[1,2,3]},]The autodecode mode tries to guess correct format based on content. This is mostly useful when you know that the data is only JSON or numbers. Arbitrary binary or string data might be accidentally decoded further than it should.Async safetyNotice that theredisobject may be shared by multiple async workers but each must obtain a separate connection by calling it, as in the examples.A connection may be stored in a variable and used for multiple commands that rely on each other, e.g. transactions. This module attempts to keep track of whether the connection is reusable and thus can be returned to connection pool.It is possible to use.prevent_poolingmodifier on a DB object to prevent its connection being pooled after use.Connection URLsThere are no separate arguments for hostname, port number and such. Instead all settings are encoded in an URL passed to Redis(). A format similar to other Redis modules is used. Some examples:redis://localhost/- default setting (localhost:6379, database 0, no auth)redis://:password@localhost/2- password authentication, using database 2rediss://secure.cloud/orredis+tls://secure.cloud/- both are the same: secure connectionredis+unix:///var/run/redis.sock?database=2- UNIX socket connection must use three slashesredis+unix+tls://hostname.on.certificate/tmp/redis.sock- why'd you want TLS on unix socket?