Skip to content

Set RedisModel.Meta.database at runtime, not import time #519

Open
@dansan

Description

@dansan

Often the software I write does not know the configuration at import time. It has to load it from multiple sources, as it is executed in different environments and with different (CLI) options.

Generally, It's best practice to not open database or network connections (or do any I/O) at import time.

Having to set the database connection at import time also makes testing harder. Things have to be patched before importing any dependency that might import the module with the RedisModel.

It would be more convenient if the database connection could be set at runtime... e.g. MyModel.Meta.database = ... when my software has finished collecting the configuration and other setup steps.

This does currently not work, because the creation of the class through the metaclass stores the value somewhere I cannot change it later.

Alternatively (and maybe less work to implement with the current code - not that I have looked at it) would be to allow the value of RedisModel.Meta.database to be a callable (type Callable[[], Redis]). That could be provided at import time without having to know the database connection yet, and would not even need patching in tests (as the test can just create a testing configuration) - it's dependency injection.

The built-in callable() can be used to test, if the value in MyModel.Meta.database is a callable. Luckily a Redis connection pool object is not a callable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions