sopherapps / pydantic-redis

A simple Declarative ORM for Redis using pydantic Models
https://sopherapps.github.io/pydantic-redis
MIT License
39 stars 14 forks source link

Allow dependency injection of Redis client #39

Closed wasperen closed 2 months ago

wasperen commented 3 months ago
          > So, this is the other way to fix the ambiguity :)

I think, having full control over the Redis instance that is used by the Store, makes more sense. It is the Dependency injection design pattern (https://en.wikipedia.org/wiki/Dependency_injection) that enables further flexibility for testing and using your package in larger systems (as we are doing).

So, it is not just for testing purposes, but also for enabling us to have full control over where, when and with what tools I am building Redis components. For instance, we are using Dependency Injection on all our components - exactly how the Redis component is constructed should not be a concern of your package. It is great, for the simple use case, to have a Redis component created on the fly. But for a larger system, where root services such as Redis are constructed in a centrally managed place, being able to inject my own Redis component is the standard.

Can I please suggest we go the way of my suggested PR?

Please create a new issue of type "Feature request" for us to weigh our options. The merged PR fixes the original issue sufficiently.

Originally posted by @Tinitto in https://github.com/sopherapps/pydantic-redis/issues/35#issuecomment-2211297650

wasperen commented 3 months ago

This PR does this https://github.com/sopherapps/pydantic-redis/pull/30

Tinitto commented 2 months ago

We need the library to be straight forward. Adding two ways of initializing the Store needs to be last resort. For now, just extend the Store

class MyStore(AbstractStore): # or MyStore(syncio.Store): or or MyStore(asyncio.Store) """My custom store"""

def __init__(
    self, name: str, redis_config: RedisConfig, redis_store: Redis, **data: Any
):
    self._redis_store = redis_store
    super().__init__(name, redis_config, **data)

def _connect_to_redis(self) -> redis.Redis:
    """Connects the store to redis.

    See base class.
    """
    return self._redis_store

store = MyStore( name="foobar", redis_config=RedisConfig(), redis_store=your_redis_instance )