Flask python - Import redis from config file

83 Views Asked by At

I have 2 environment and one of the environment is clusterdisabled, the other is cluster enabled. To handle this, i added a key in config For one of the environment it's

redis_class = "Redis"

The other environment has

redis_class = "RedisCluster"

init.py

 from myapp.config import config
 #this printed the value 
 print(config["redis_class")
 redis_class = config["redis_class"]
 from redis import redis_class as Redis

The last line in init.py is throwing an error. How do I import classes from config?

Thanks in advance

2

There are 2 best solutions below

3
shaik moeed On BEST ANSWER

You can try out something like this,

redis_class = config["redis_class"]
if redis_class == 'Redis':
    from redis import Redis
else:
    from redis import RedisCluster as Redis

or keep the above code in another file(config.py) and in your main file you can import it directly.

like from config import Redis


Without using if-condition you can try with getattr like this

import redis

redis_class = config["redis_class"]
Redis = getattr(redis, redis_class) 

# use the redis class as normal
Redis(...)
1
Vyshnavi On
__import__("redis", fromlist=["RedisCluster"])