Skip to main content

Wrapper de conveniência para Redis - conexão, JSON helpers e reconexão automática

Project description

redis-simplify

PyPI Version Python Versions License

A lightweight synchronous convenience wrapper for Redis built on top of redis-py.

redis-simplify was created to reduce repetitive Redis boilerplate in Python applications by providing a simple and consistent interface with automatic reconnection, JSON helpers, centralized logging, and defensive error handling.

This package is not a Redis client replacement. It is a convenience layer built on top of redis-py to simplify common Redis operations.


Features

  • Explicit Redis configuration (host, port, password, db)

  • Does not automatically read .env files

  • Automatic reconnection when Redis becomes unavailable

  • Centralized logging and error handling

  • JSON helpers for storing Python dictionaries

  • Safe fallback values on failures

  • Fully tested with pytest

  • Lightweight implementation

  • Synchronous API

  • Support for the most commonly used Redis operations:

    • Strings
    • Sets
    • Hashes
    • Lists
    • Pipelines
    • SCAN iteration

Installation

pip install redis-simplify

Requirements

  • Python >= 3.8
  • redis-py >= 4.0.0

Quick Start

from redis_simplify import RedisClient

client = RedisClient(
    host="localhost",
    port=6379
)

Basic Usage

Strings

from redis_simplify import RedisClient

client = RedisClient(host="localhost", port=6379)

client.set("chave", "valor")

print(client.get("chave"))

Output:

valor

JSON Helpers

Store Python dictionaries directly in Redis.

client.set_json(
    "usuario:1",
    {
        "nome": "João",
        "idade": 30
    }
)

print(client.get_json("usuario:1"))

Output:

{
    "nome": "João",
    "idade": 30
}

Sets

client.sadd("tags", "python", "redis")

print(client.smembers("tags"))

Possible output:

{"python", "redis"}

Connection Check

if client.ping():
    print("Redis online")
else:
    print("Redis unavailable")

Automatic Reconnection

Before executing operations, the client verifies the connection status.

If Redis becomes unavailable, the wrapper automatically attempts to reconnect before executing the requested command.

This behavior is transparent to application code and helps reduce connection-management boilerplate.


Error Handling

All operations include consistent exception handling and logging.

Instead of propagating Redis exceptions, the wrapper logs errors and returns safe fallback values whenever possible.

Fallback Values

Return Type Fallback
Object / String None
Boolean False
Numeric 0
List []
Dictionary {}
Set set()

This approach helps keep application code clean and reduces repetitive try/except blocks.


Available Methods

Strings

Method Description
set(key, value, expire_seconds=None) Set a value
get(key) Retrieve a value
delete(*keys) Delete one or more keys
exists(key) Check if a key exists
expire(key, seconds) Set expiration time
incr(key) Increment a value
decr(key) Decrement a value

JSON

Method Description
set_json(key, data, expire_seconds=None) Store a dictionary as JSON
get_json(key) Retrieve and deserialize JSON

Sets

Method Description
sadd(key, *values) Add members
srem(key, *values) Remove members
smembers(key) Retrieve all members
sismember(key, value) Check membership
scard(key) Count members

Hashes

Method Description
hset(key, field, value) Set a hash field
hget(key, field) Retrieve a field
hgetall(key) Retrieve all fields

Lists

Method Description
lpush(key, *values) Push values to the beginning
rpush(key, *values) Push values to the end
lrange(key, start, end) Retrieve a range of values

Utilities

Method Description
ping() Verify connectivity
pipeline() Create a Redis pipeline
scan(cursor=0, match=None, count=None) Iterate keys using SCAN
flush_all() Remove all Redis databases
close() Close the connection

Pipeline Example

pipe = client.pipeline()

pipe.set("user:1", "John")
pipe.set("user:2", "Jane")

pipe.execute()

SCAN Example

cursor = 0

while True:
    cursor, keys = client.scan(
        cursor=cursor,
        match="user:*",
        count=100
    )

    print(keys)

    if cursor == 0:
        break

Shared Instance Pattern

redis-simplify does not enforce a Singleton pattern.

However, many applications create a single shared instance and reuse it throughout the project:

from redis_simplify import RedisClient

redis_client = RedisClient(
    host="localhost",
    port=6379
)

Why redis-simplify?

Many projects repeatedly implement:

  • Redis connection setup
  • Health checks
  • Reconnection logic
  • JSON serialization and deserialization
  • Logging
  • Defensive exception handling

redis-simplify centralizes these concerns into a small reusable wrapper while preserving the familiar Redis workflow provided by redis-py.


Running Tests

The project includes automated tests built with pytest.

pytest

Contributing

Contributions are welcome.

To contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add or update tests when applicable
  5. Open a Pull Request

Bug reports, improvements, and feature suggestions are appreciated.


License

This project is licensed under the MIT License.


Author

Paulo Ricardo Tebet Lyrio

GitHub: https://github.com/Paulouuul/redis-simplify

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

redis_simplify-0.1.0.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

redis_simplify-0.1.0-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file redis_simplify-0.1.0.tar.gz.

File metadata

  • Download URL: redis_simplify-0.1.0.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for redis_simplify-0.1.0.tar.gz
Algorithm Hash digest
SHA256 656c776653e59da9fe104d6265274de4fd4966b750e3ee63d2c0c973c4d968c0
MD5 57fa141359b2476ee73bf10c9b4951d9
BLAKE2b-256 8eadcc5429a241c296e798e300605a5f5914de1a38976aca97ecc337362ba18d

See more details on using hashes here.

File details

Details for the file redis_simplify-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: redis_simplify-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for redis_simplify-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ba230b83606cd663986a1f6a194baad22629a55206ea8d20903afb1db31b68e
MD5 9005886e721c587ebf033daff8e73a31
BLAKE2b-256 0f4201977d144cb340f81d5bf167b81d7938ac02e6137e63aa1410baf442f138

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page