杰瑞科技汇

Python Redis 如何配置认证?

Of course! Here’s a comprehensive guide to using Redis authentication in Python, covering the basics, connection methods, best practices, and troubleshooting.

Python Redis 如何配置认证?-图1
(图片来源网络,侵删)

The Core Concept: Redis Authentication

By default, Redis allows connections without a password. However, for any production environment, you must enable authentication to secure your database.

Authentication in Redis works in two main ways:

  1. Simple Password (Most Common): You set a single password for the entire Redis server. All clients must provide this same password.
  2. Username/Password (Redis 6.0+): This is more secure, allowing you to define multiple users with different roles and permissions (e.g., read-only users).

Setting Up Authentication on the Redis Server

Before you can connect with Python, your Redis server needs to be configured to require a password.

Method A: Simple Password (Recommended for most use cases)

  1. Edit the Redis Configuration File: Open your redis.conf file (usually located at /etc/redis/redis.conf on Linux or in the root of your Redis installation directory).

    Python Redis 如何配置认证?-图2
    (图片来源网络,侵删)
  2. Uncomment and Set the Password: Find the # requirepass foobared line. Uncomment it and change foobared to your strong password.

    # /path/to/your/redis.conf
    # To require clients to issue AUTH <PASSWORD> before processing any other
    # commands, uncomment the following line:
    #
    # requirepass your_strong_password_here

    Change it to:

    requirepass my_super_secret_password_123
  3. Restart Redis: For the changes to take effect, you must restart the Redis server.

    # For systems using systemd
    sudo systemctl restart redis
    # Or using the redis-server command directly
    redis-server /path/to/your/redis.conf

Method B: Username/Password (Redis 6.0+)

This is more complex to set up but offers better security. You typically create users using the ACL (Access Control List) commands directly in the Redis CLI.

# Connect to Redis without a password first (e.g., via Docker or local dev)
redis-cli
# In the Redis CLI:
# 1. Create a new user named 'app_user' with a password and full permissions
> ACL SETUSER app_user on >my_app_password ~* &* +@all
# 2. (Optional) Create a read-only user
> ACL SETUSER readonly_user on >readonly_password ~* &* +@read +@info
  • on: Enables the user.
  • >my_app_password: Sets the password.
  • Sets the default user key pattern to all keys ().
  • &*: Sets the user channel pattern to all channels.
  • +@all: Grants all commands.
  • +@read: Grants read-only commands.

Connecting from Python with Authentication

The most popular Python Redis client is redis-py. You'll need to install it first:

pip install redis

Here’s how to connect using the simple password method.

Basic Connection with a Password

This is the most straightforward approach. You pass the password directly to the Redis constructor.

import redis
# The password you set in redis.conf
REDIS_PASSWORD = "my_super_secret_password_123"
try:
    # The 'password' argument is used for authentication
    r = redis.Redis(
        host='localhost',
        port=6379,
        password=REDIS_PASSWORD,
        decode_responses=True  # Automatically decode bytes to strings
    )
    # Test the connection
    r.ping()
    print("Successfully connected to Redis!")
    # Now you can use Redis commands
    r.set("auth_key", "This is a secure value.")
    value = r.get("auth_key")
    print(f"Value for 'auth_key': {value}")
except redis.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except redis.ConnectionError as e:
    print(f"Could not connect to Redis: {e}")

Connection with Username and Password (Redis 6.0+)

If your Redis server uses the newer username/password authentication, you use the username argument.

import redis
REDIS_USERNAME = "app_user"
REDIS_PASSWORD = "my_app_password"
try:
    # The 'username' and 'password' arguments are used for authentication
    r = redis.Redis(
        host='localhost',
        port=6379,
        username=REDIS_USERNAME,
        password=REDIS_PASSWORD,
        decode_responses=True
    )
    # Test the connection
    r.ping()
    print(f"Successfully connected as user '{REDIS_USERNAME}'!")
    # You can verify the user's identity
    user_info = r.execute_command("ACL WHOAMI")
    print(f"Current user: {user_info}")
except redis.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except redis.ConnectionError as e:
    print(f"Could not connect to Redis: {e}")

Best Practices and Advanced Configuration

For production applications, hardcoding credentials is a bad idea. Use environment variables or a secrets management system.

Using Environment Variables

import os
import redis
from dotenv import load_dotenv # pip install python-dotenv
# Load variables from a .env file
load_dotenv()
# Get credentials from environment variables
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_USER = os.getenv("REDIS_USER")
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD")
# Construct the connection URL
# redis://username:password@host:port/db
if REDIS_USER:
    redis_url = f"redis://{REDIS_USER}:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/0"
else:
    redis_url = f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/0"
try:
    # The 'from_url' method is a clean way to connect
    r = redis.from_url(redis_url, decode_responses=True)
    r.ping()
    print("Successfully connected to Redis using a URL!")
except redis.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

Using a Connection Pool

Creating a new connection for every operation is inefficient. A ConnectionPool manages a set of reusable connections, significantly improving performance.

import redis
REDIS_PASSWORD = "my_super_secret_password_123"
# Create a connection pool
# This pool can be shared across your application
pool = redis.ConnectionPool(
    host='localhost',
    port=6379,
    password=REDIS_PASSWORD,
    decode_responses=True,
    max_connections=20  # Adjust based on your needs
)
# Get a connection from the pool
r = redis.Redis(connection_pool=pool)
# Use the connection as usual
r.set("pool_key", "value from pooled connection")
print(r.get("pool_key"))

Troubleshooting Common Errors

Error Message Cause Solution
redis.exceptions.AuthenticationError: Invalid password The password you provided is incorrect. Double-check your password. Ensure it matches exactly what you set in redis.conf or created with ACL SETUSER.
redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused. Python cannot reach the Redis server. Is the Redis server running? Is the host (localhost) and port (6379) correct? If Redis is running in a Docker container, you might need to use the container's IP address or a port mapping.
redis.exceptions.AuthenticationError: NOAUTH Authentication required. You connected to a Redis server that has a password set, but you didn't provide one. Make sure your Python code includes the password argument in the Redis() constructor.
redis.exceptions.ResponseError: WRONGPASS invalid username-password pair You are using username/password authentication, but the combination is wrong. Verify both the username and password are correct. Check if the user exists and is enabled (on).
分享:
扫描分享到社交APP
上一篇
下一篇