Python connects to redis database (authentication mode)

Table of contents

1. Connection method

2. How to use

3. Possible situations

Check the redis module version:

 Upgrade the redis module version:


 1. Connection method

import redis

def connect_redis(host, port, username, password, db):
    """
    连接 Redis 数据库
    :param host: Redis 主机地址
    :param port: Redis 端口号
    :param username: Redis 用户名
    :param password: Redis 密码
    :param db: Redis 数据库编号
    :return: 如果连接成功,则返回 Redis 对象,否则返回 None
    """
    try:
        r = redis.Redis(host=host, port=port, db=db, password=password)
        print( r.ping())   # 测试连接是否正常
        return r
    except Exception as e:
        print('Redis 连接失败:', e)
        return None

2. How to use

if __name__ == '__main__':
    redis_host = 'localhost'  # Redis 主机地址
    redis_port = 6379  # Redis 端口号
    redis_username = 'default'  # Redis 用户名
    redis_password = '123456'  # Redis 密码
    db = 0  # Redis 数据库编号

    r = connect_redis(redis_host, redis_port, redis_username, redis_password, db)
    if r:
        r.set('test_key', '123456')
        result = r.get('test_key')
        print(result)
    else:
        print('Redis 连接失败')

3. Possible situations

Error: Redis connection failed: init () got an unexpected keyword argument 'username' 

This error is reported because the version of the Redis module is too low to support  username and  password parameters. If you are using an older version of  redis the module, you can try upgrading to the latest version.

Check the redis module version:

pip show redis

 Upgrade the redis module version:

pip install redis --upgrade

Guess you like

Origin blog.csdn.net/qq_19309473/article/details/130377541