aioredis api——reference
Connection usage is as simple as:
import asyncio
import aioredis
async def connect_uri():
conn = await aioredis.create_connection(
'redis://localhost/0')
val = await conn.execute('GET', 'my-key')
async def connect_tcp():
conn = await aioredis.create_connection(
('localhost', 6379))
val = await conn.execute('GET', 'my-key')
async def connect_unixsocket():
conn = await aioredis.create_connection(
'/path/to/redis/socket')
# or uri 'unix:///path/to/redis/socket?db=1'
val = await conn.execute('GET', 'my-key')
asyncio.get_event_loop().run_until_complete(connect_tcp())
asyncio.get_event_loop().run_until_complete(connect_unixsocket())
coroutine aioredis.create_connection(address, *, db=0, password=None, ssl=None, encoding=None, parser=None, loop=None, timeout=None)
Creates Redis connection.
Parameters:
- address (tuple or str) – An address where to connect. Can be one of
the following:
a Redis URI — “redis://host:6379/0?encoding=utf- 8”;“redis://:password@host:6379/0?encoding=utf-8”;
a (host, port) tuple — (‘localhost’, 6379);
or a unix domain socket path string — “/path/to/redis.sock”.* - db (int) – Redis database index to switch to when connected.
- password (str or None) – Password to use if redis server instance
requires authorization. - ssl (ssl.SSLContext or True or None) – SSL context that is passed
through to asyncio.BaseEventLoop.create_connection(). - encoding (str or None) – Codec to use for response decoding.
- parser (callable or None) – Protocol parser class. Can be used to set
custom protocol reader; expected same interface as hiredis.Reader. - loop (EventLoop) – An optional event loop instance (uses
asyncio.get_event_loop() if not specified). - timeout (float greater than 0 or None) – Max time to open a
connection, otherwise raise asyncio.TimeoutError exception. None by
default
Returns: RedisConnection instance.
-
class
-
Bases:
abc.AbcConnection
Redis connection interface.
-
Redis server address; either IP-port tuple or unix socket str (read-only). IP is either IPv4 or IPv6 depending on resolved host part in initial address.
New in version v0.2.8.
address
¶ -
aioredis.
RedisConnection
¶
-
Current database index (read-only).
db
¶
-
Current codec for response decoding (read-only).
encoding
¶
-
Set to
True
if connection is closed (read-only).
closed
¶
-
Set to
True
when MULTI command was issued (read-only).
in_transaction
¶
-
Read-only dict with subscribed channels. Keys are bytes, values are
Channel
instances.
pubsub_channels
¶
-
Read-only dict with subscribed patterns. Keys are bytes, values are
Channel
instances.
pubsub_patterns
¶
-
Indicates that connection is in PUB/SUB mode. Provides the number of subscribed channels. Read-only.
in_pubsub
¶
-
Execute Redis command.
The method is not a coroutine itself but instead it writes to underlying transport and returns a
asyncio.Future
waiting for result.Parameters: Raises: - TypeError – When any of arguments is None or can not be encoded as bytes.
- aioredis.ReplyError – For redis error replies.
- aioredis.ProtocolError – When response can not be decoded and/or connection is broken.
Returns: Returns bytes or int reply (or str if encoding was set)
execute
(
command,
*args,
encoding=_NOTSET
)
¶
-
Method to execute Pub/Sub commands. The method is not a coroutine itself but returns a
asyncio.gather()
coroutine. Method also acceptaioredis.Channel
instances as command arguments:>>> ch1 = Channel('A', is_pattern=False, loop=loop) >>> await conn.execute_pubsub('subscribe', ch1) [[b'subscribe', b'A', 1]]
Changed in version v0.3: The method accept
Channel
instances.Parameters: Returns: Returns a list of subscribe/unsubscribe messages, ex:
>>> await conn.execute_pubsub('subscribe', 'A', 'B') [[b'subscribe', b'A', 1], [b'subscribe', b'B', 2]]
execute_pubsub
(
command,
*channels_or_patterns
)
¶
-
Closes connection.
Mark connection as closed and schedule cleanup procedure.
All pending commands will be canceled with
ConnectionForcedCloseError
.
close
(
)
¶
-
Coroutine waiting for connection to get closed.
wait_closed
(
)
¶
-
Changes current db index to new one.
Parameters: db (int) – New redis database index.
Raises: - TypeError – When
db
parameter is not int. - ValueError – When
db
parameter is less than 0.
Return True: Always returns True or raises exception.
- TypeError – When
select
(
db
)
¶
-
Send AUTH command.
Parameters: password (str) – Plain-text password Return bool: True if redis replied with ‘OK’.
auth
(
password
)
¶
Commands Interface
The library provides high-level API implementing simple interface to Redis commands.
The usage is as simple as:
import aioredis
# Create Redis client bound to single non-reconnecting connection.
async def single_connection():
redis = await aioredis.create_redis(
'redis://localhost')
val = await redis.get('my-key')
# Create Redis client bound to connections pool.
async def pool_of_connections():
redis = await aioredis.create_redis_pool(
'redis://localhost')
val = await redis.get('my-key')
# we can also use pub/sub as underlying pool
# has several free connections:
ch1, ch2 = await redis.subscribe('chan:1', 'chan:2')
# publish using free connection
await redis.publish('chan:1', 'Hello')
await ch1.get()
Connections pool example
import asyncio
import aioredis
async def main():
pool = await aioredis.create_pool(
'redis://localhost',
minsize=5, maxsize=10)
with await pool as conn: # low-level redis connection
await conn.execute('set', 'my-key', 'value')
val = await conn.execute('get', 'my-key')
print('raw value:', val)
pool.close()
await pool.wait_closed() # closing all open connections
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
Command Example
import asyncio
import aioredis
async def main():
# Redis client bound to single connection (no auto reconnection).
redis = await aioredis.create_redis(
'redis://localhost')
await redis.set('my-key', 'value')
val = await redis.get('my-key')
print(val)
# gracefully closing underlying connection
redis.close()
await redis.wait_closed()
async def redis_pool():
# Redis client bound to pool of connections (auto-reconnecting).
redis = await aioredis.create_redis_pool(
'redis://localhost')
await redis.set('my-key', 'value')
val = await redis.get('my-key')
print(val)
# gracefully closing underlying connection
redis.close()
await redis.wait_closed()
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_until_complete(redis_pool())