Python-aioredis

本文档介绍了如何使用Python的aioredis库创建连接,包括通过coroutine创建Redis连接的参数说明,如地址、数据库索引、密码和SSL设置。此外,还提到了高阶API,提供了简单易用的Redis命令接口,以及连接池和命令示例。
摘要由CSDN通过智能技术生成

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 aioredis. RedisConnection

Bases: abc.AbcConnection

Redis connection interface.

address

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.

db

Current database index (read-only).

encoding

Current codec for response decoding (read-only).

closed

Set to True if connection is closed (read-only).

in_transaction

Set to True when MULTI command was issued (read-only).

pubsub_channels

Read-only dict with subscribed channels. Keys are bytes, values are Channel instances.

pubsub_patterns

Read-only dict with subscribed patterns. Keys are bytes, values are Channel instances.

in_pubsub

Indicates that connection is in PUB/SUB mode. Provides the number of subscribed channels. Read-only.

execute ( command, *args, encoding=_NOTSET )

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:
  • command (str, bytes, bytearray) – Command to execute
  • encoding (str or None) – Keyword-only argument for overriding response decoding. By default will use connection-wide encoding. May be set to None to skip response decoding.
Raises:
Returns:

Returns bytes or int reply (or str if encoding was set)

execute_pubsub ( command, *channels_or_patterns )

Method to execute Pub/Sub commands. The method is not a coroutine itself but returns a asyncio.gather() coroutine. Method also accept aioredis.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:
  • command (str, bytes, bytearray) – One of the following Pub/Sub commands: subscribe, unsubscribe, psubscribe, punsubscribe.
  • *channels_or_patterns – Channels or patterns to subscribe connection to or unsubscribe from. At least one channel/pattern is required.
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]]

close ( )

Closes connection.

Mark connection as closed and schedule cleanup procedure.

All pending commands will be canceled with ConnectionForcedCloseError.

wait_closed ( )

Coroutine waiting for connection to get closed.

select ( db )

Changes current db index to new one.

Parameters:

db (int) – New redis database index.

Raises:
Return True:

Always returns True or raises exception.

auth ( password )

Send AUTH command.

Parameters:password (str) – Plain-text password
Return bool:True if redis replied with ‘OK’.

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())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值