Examples of aioredis usage

Below is a list of examples from aioredis/examples (see for more).

Every example is a correct python program that can be executed.

Commands example

get source code

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.run(main())
    asyncio.run(redis_pool())

Transaction example

get source code

import asyncio
import aioredis


async def main():
    redis = await aioredis.create_redis(
        'redis://localhost')
    await redis.delete('foo', 'bar')
    tr = redis.multi_exec()
    fut1 = tr.incr('foo')
    fut2 = tr.incr('bar')
    res = await tr.execute()
    res2 = await asyncio.gather(fut1, fut2)
    print(res)
    assert res == res2

    redis.close()
    await redis.wait_closed()


if __name__ == '__main__':
    asyncio.run(main())

Pub/Sub example

get source code

import asyncio
import aioredis


async def reader(ch):
    while (await ch.wait_message()):
        msg = await ch.get_json()
        print("Got Message:", msg)


async def main():
    pub = await aioredis.create_redis(
        'redis://localhost')
    sub = await aioredis.create_redis(
        'redis://localhost')
    res = await sub.subscribe('chan:1')
    ch1 = res[0]

    tsk = asyncio.ensure_future(reader(ch1))

    res = await pub.publish_json('chan:1', ["Hello", "world"])
    assert res == 1

    await sub.unsubscribe('chan:1')
    await tsk
    sub.close()
    pub.close()


if __name__ == '__main__':
    asyncio.run(main())

Scan command example

get source code

import asyncio
import aioredis


async def main():
    """Scan command example."""
    redis = await aioredis.create_redis(
        'redis://localhost')

    await redis.mset('key:1', 'value1', 'key:2', 'value2')
    cur = b'0'  # set initial cursor to 0
    while cur:
        cur, keys = await redis.scan(cur, match='key:*')
        print("Iteration results:", keys)

    redis.close()
    await redis.wait_closed()


if __name__ == '__main__':
    import os
    if 'redis_version:2.6' not in os.environ.get('REDIS_VERSION', ''):
        asyncio.run(main())

Sentinel client

get source code

import asyncio
import aioredis


async def main():
    sentinel_client = await aioredis.create_sentinel(
        [('localhost', 26379)])

    master_redis = sentinel_client.master_for('mymaster')
    info = await master_redis.role()
    print("Master role:", info)
    assert info.role == 'master'

    sentinel_client.close()
    await sentinel_client.wait_closed()


if __name__ == '__main__':
    asyncio.run(main())

Low-level connection usage example

get source code

import asyncio
import aioredis


async def main():
    conn = await aioredis.create_connection(
        'redis://localhost', encoding='utf-8')

    ok = await conn.execute('set', 'my-key', 'some value')
    assert ok == 'OK', ok

    str_value = await conn.execute('get', 'my-key')
    raw_value = await conn.execute('get', 'my-key', encoding=None)
    assert str_value == 'some value'
    assert raw_value == b'some value'

    print('str value:', str_value)
    print('raw value:', raw_value)

    # optionally close connection
    conn.close()
    await conn.wait_closed()


if __name__ == '__main__':
    asyncio.run(main())

Connections pool example

get source code

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.run(main())