I am building a Flask server in Python and have a CustomRedis
class with set(key, value)
and get(key)
methods.
This class adds a user-specific prefix before storing keys in the Redis database, allowing user-specific data storage without using Flask’s default session.
I am wondering about the best structure for service classes. Which approach is recommended?
Classic: Functions only
cache = CustomRedis()
def hello_world():
return "Hi " + cache.get("user_pseudo")
Pros: Easy to use, default structure. Cons: Global variables can lead to concurrency issues.
Singleton
class SingletonMeta(type):
# See Refactoring for example
class ServiceHelloWorld(metaclass=SingletonMeta):
def __init__(self):
self.cache = CustomRedis()
def hello_world(self):
return "Hi " + self.cache.get("user_pseudo")
Pros: Better code decomposition using classes. Cons: self.cache is long to write each time.
Static Class
class ServiceHelloWorld:
cache = CustomRedis()
@staticmethod
def hello_world():
return "Hi " + ServiceHelloWorld.cache.get("user_pseudo")
Pros: Easier than Singleton to implement. Cons: ServiceHelloWorld is long to write each time.
Which structure is best suited for this use case? Are there better alternatives?