Convert Figma logo to code with AI

redis logoredis-py

Redis Python client

12,530
2,504
12,530
252

Top Related Projects

12,531

Redis Python client

asyncio (PEP 3156) Redis support

Redis management tool written in node.js

66,270

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.

Redis Node.js client

Quick Overview

Redis-py is the official Python client library for Redis, an open-source, in-memory data structure store. It provides a Pythonic interface to interact with Redis, supporting various data structures and features offered by Redis, including strings, hashes, lists, sets, sorted sets, and more.

Pros

  • Comprehensive support for Redis commands and data structures
  • Efficient connection pooling for improved performance
  • Support for Redis Cluster, Sentinel, and SSL connections
  • Active development and maintenance by the Redis community

Cons

  • Limited built-in support for advanced Redis features like Lua scripting
  • Some users report occasional issues with connection handling in high-concurrency scenarios
  • Documentation can be sparse for some advanced use cases

Code Examples

  1. Basic key-value operations:
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')
print(value)  # Output: b'bar'
  1. Working with lists:
r.lpush('my_list', 'item1', 'item2', 'item3')
items = r.lrange('my_list', 0, -1)
print(items)  # Output: [b'item3', b'item2', b'item1']
  1. Using hash structures:
r.hset('user:1', mapping={'name': 'John', 'age': '30', 'city': 'New York'})
user_data = r.hgetall('user:1')
print(user_data)  # Output: {b'name': b'John', b'age': b'30', b'city': b'New York'}
  1. Pub/Sub functionality:
pubsub = r.pubsub()
pubsub.subscribe('my_channel')

# In another part of the code or another process:
r.publish('my_channel', 'Hello, Redis!')

# Listening for messages:
for message in pubsub.listen():
    if message['type'] == 'message':
        print(f"Received: {message['data']}")

Getting Started

To get started with redis-py, follow these steps:

  1. Install redis-py using pip:

    pip install redis
    
  2. Import the library and create a Redis connection:

    import redis
    r = redis.Redis(host='localhost', port=6379, db=0)
    
  3. Start using Redis commands:

    r.set('key', 'value')
    result = r.get('key')
    print(result)  # Output: b'value'
    

For more advanced usage, refer to the official documentation and examples provided in the GitHub repository.

Competitor Comparisons

12,531

Redis Python client

Pros of redis-py

  • Widely adopted and well-maintained official Redis client for Python
  • Comprehensive feature set covering most Redis functionality
  • Extensive documentation and community support

Cons of redis-py

  • Larger codebase, potentially more complex for simple use cases
  • May have slower performance for certain operations compared to optimized alternatives

Code Comparison

redis-py:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')

redis-py:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')

Summary

Both redis-py and redis-py are the same repository. The comparison provided above is between redis-py and a hypothetical alternative client. redis-py is the official Python client for Redis, offering a comprehensive set of features and robust community support. While it may have a larger codebase compared to simpler alternatives, it provides a reliable and well-documented solution for interacting with Redis in Python applications.

asyncio (PEP 3156) Redis support

Pros of aioredis-py

  • Designed specifically for asynchronous programming with asyncio
  • Supports Redis Cluster and Sentinel configurations out of the box
  • Offers more fine-grained control over connection pooling

Cons of aioredis-py

  • Less actively maintained (abandoned) compared to redis-py
  • Smaller community and fewer resources available
  • May lack support for some newer Redis features

Code Comparison

redis-py (synchronous):

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')

aioredis-py (asynchronous):

import aioredis
import asyncio

async def main():
    redis = await aioredis.create_redis_pool('redis://localhost')
    await redis.set('foo', 'bar')
    value = await redis.get('foo')
    redis.close()
    await redis.wait_closed()

asyncio.run(main())

The main difference is that aioredis-py uses async/await syntax for asynchronous operations, while redis-py uses synchronous methods. aioredis-py requires explicit connection management, whereas redis-py handles connections more implicitly.

Redis management tool written in node.js

Pros of Redis Commander

  • Provides a web-based GUI for Redis management
  • Supports multiple Redis connections and databases
  • Offers a user-friendly interface for data visualization and manipulation

Cons of Redis Commander

  • Limited to management and visualization tasks, not a full-featured Redis client
  • May have higher resource usage due to its web-based nature
  • Less suitable for programmatic interactions with Redis

Code Comparison

Redis Commander (JavaScript):

const express = require('express');
const redisCommander = require('redis-commander');
const app = express();
redisCommander.initializeMiddleware(app);
app.listen(8081);

redis-py (Python):

import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')
print(value)

Summary

Redis Commander is a web-based GUI tool for Redis management, offering visual data manipulation and multiple connection support. It's ideal for users who prefer graphical interfaces but may not be suitable for programmatic interactions. On the other hand, redis-py is a Python client library for Redis, providing direct programmatic access to Redis functionality. It's more suitable for integration into Python applications but lacks the visual management features of Redis Commander.

66,270

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.

Pros of redis

  • Written in C, offering high performance and low-level optimizations
  • Serves as the official Redis server implementation
  • Provides a comprehensive set of Redis features and commands

Cons of redis

  • Requires compilation and system-level installation
  • Higher complexity for contributing and understanding the codebase
  • Not directly usable as a client library in most programming languages

Code comparison

redis (server-side Lua script):

local key = KEYS[1]
local value = redis.call('GET', key)
if value then
    return value
else
    return redis.call('SET', key, ARGV[1])
end

redis-py (Python client):

def get_or_set(redis_client, key, default_value):
    value = redis_client.get(key)
    if value is None:
        redis_client.set(key, default_value)
        return default_value
    return value

The redis example shows a Lua script that can be executed on the server-side, while the redis-py example demonstrates how to achieve similar functionality using the Python client library.

Redis Node.js client

Pros of node-redis

  • Asynchronous by default, leveraging Node.js event-driven architecture
  • Extensive middleware support for custom command transformations
  • Built-in support for Redis Streams

Cons of node-redis

  • Limited support for older Redis versions (focuses on Redis 6+)
  • Steeper learning curve for developers new to Node.js async patterns

Code Comparison

node-redis:

import { createClient } from 'redis';

const client = createClient();
await client.connect();

await client.set('key', 'value');
const value = await client.get('key');

redis-py:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('key', 'value')
value = r.get('key')

Both libraries provide similar functionality for basic Redis operations. node-redis uses async/await syntax by default, while redis-py offers a more synchronous-style API (though it also supports async operations).

node-redis is well-suited for Node.js applications, especially those leveraging Redis 6+ features and requiring high-performance asynchronous operations. redis-py is more appropriate for Python developers and offers broader compatibility with older Redis versions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

redis-py

The Python interface to the Redis key-value store.

CI docs MIT licensed pypi pre-release codecov

Installation | Usage | Advanced Topics | Contributing


**Note: ** redis-py 5.0 will be the last version of redis-py to support Python 3.7, as it has reached end of life. redis-py 5.1 will support Python 3.8+.


How do I Redis?

Learn for free at Redis University

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Installation

Start a redis via docker:

docker run -p 6379:6379 -it redis/redis-stack:latest

To install redis-py, simply:

$ pip install redis

For faster performance, install redis with hiredis support, this provides a compiled response parser, and for most cases requires zero code changes. By default, if hiredis >= 1.0 is available, redis-py will attempt to use it for response parsing.

$ pip install "redis[hiredis]"

Looking for a high-level library to handle object mapping? See redis-om-python!

Supported Redis Versions

The most recent version of this library supports redis version 5.0, 6.0, 6.2, 7.0, 7.2 and 7.4.

The table below highlights version compatibility of the most-recent library versions and redis versions.

Library versionSupported redis versions
3.5.3<= 6.2 Family of releases
>= 4.5.0Version 5.0 to 7.0
>= 5.0.0Version 5.0 to current

Usage

Basic Example

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

The above code connects to localhost on port 6379, sets a value in Redis, and retrieves it. All responses are returned as bytes in Python, to receive decoded strings, set decode_responses=True. For this, and more connection options, see these examples.

RESP3 Support

To enable support for RESP3, ensure you have at least version 5.0 of the client, and change your connection object to include protocol=3

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0, protocol=3)

Connection Pools

By default, redis-py uses a connection pool to manage connections. Each instance of a Redis class receives its own connection pool. You can however define your own redis.ConnectionPool.

>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)

Alternatively, you might want to look at Async connections, or Cluster connections, or even Async Cluster connections.

Redis Commands

There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HSET, HGETALL, etc.) except where a word (i.e. del) is reserved by the language. The complete set of commands can be found here, or the documentation.

Advanced Topics

The official Redis command documentation does a great job of explaining each command in detail. redis-py attempts to adhere to the official command syntax. There are a few exceptions:

  • MULTI/EXEC: These are implemented as part of the Pipeline class. The pipeline is wrapped with the MULTI and EXEC statements by default when it is executed, which can be disabled by specifying transaction=False. See more about Pipelines below.

  • SUBSCRIBE/LISTEN: Similar to pipelines, PubSub is implemented as a separate class as it places the underlying connection in a state where it can't execute non-pubsub commands. Calling the pubsub method from the Redis client will return a PubSub instance where you can subscribe to channels and listen for messages. You can only call PUBLISH from the Redis client (see this comment on issue #151 for details).

For more details, please see the documentation on advanced topics page.

Pipelines

The following is a basic example of a Redis pipeline, a method to optimize round-trip calls, by batching Redis commands, and receiving their results as a list.

>>> pipe = r.pipeline()
>>> pipe.set('foo', 5)
>>> pipe.set('bar', 18.5)
>>> pipe.set('blee', "hello world!")
>>> pipe.execute()
[True, True, True]

PubSub

The following example shows how to utilize Redis Pub/Sub to subscribe to specific channels.

>>> r = redis.Redis(...)
>>> p = r.pubsub()
>>> p.subscribe('my-first-channel', 'my-second-channel', ...)
>>> p.get_message()
{'pattern': None, 'type': 'subscribe', 'channel': b'my-second-channel', 'data': 1}

Author

redis-py is developed and maintained by Redis Inc. It can be found here, or downloaded from pypi.

Special thanks to:

  • Andy McCurdy (sedrik@gmail.com) the original author of redis-py.
  • Ludovico Magnocavallo, author of the original Python Redis client, from which some of the socket code is still used.
  • Alexander Solovyov for ideas on the generic response callback system.
  • Paul Hubbard for initial packaging support.

Redis