Created
November 17, 2021 14:53
-
-
Save OmarIthawi/5fc236820901cb740a966eee231e2745 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
min. Requirements: | |
- We an API client that fetches configs from the API. | |
- We need it to cache the result via Django cache, and use cache when possible. | |
adl. Requirements: | |
- Allow using the client in packages (such CLI) that Django isn't installed. | |
""" | |
## v1. Hard Django Depdencency in a single class | |
# client.py | |
from django.core.cache import cache | |
class MyClient: | |
def __init__(self, url): | |
pass | |
def get_configs(self, uuid): | |
# There's no way to use this class outside Django | |
cached_value = cache.get(uuid) | |
if cached_value: | |
return cached_value | |
else: | |
fresh_value = requests.get(self.url + '/' + uuid) | |
cache.set(uuid, fresh_value) | |
return fresh_value | |
## v2. Two classes, one for Django and another one for generic | |
# client_attempt2.py | |
class MyBaseClient: | |
def __init__(self, url): | |
pass | |
def get_configs(self, uuid): | |
return requests.get(self.url + '/' + uuid) | |
# client_django_attempt2.py | |
class MyDjangoClient(MyBaseClient): | |
def get_configs(self, uuid): | |
# There's no way to use this class outside Django | |
cached_value = cache.get(uuid) | |
if cached_value: | |
return cached_value | |
else: | |
fresh_value = super().get_configs(uuid) | |
cache.set(uuid, fresh_value) | |
return fresh_value | |
class MyDjangoClientWithBucket: | |
pass | |
class MyRedisClientWithBucket: | |
pass | |
class MyRedisClient: | |
pass | |
class MyClientWithBucket: | |
pass | |
## v3. Two classes composision (or it can be called depedency injection) | |
# client_attempt3.py | |
class MyClient: | |
def __init__(self, url, cache=None, bucket=None): | |
pass | |
def get_configs(self, uuid): | |
if self.cache: | |
cached_value = self.cache.get(uuid) | |
if cached_value: | |
return cached_value | |
fresh_value = requests.get(self.url + '/' + uuid) | |
if self.cache: | |
self.cache.set(uuid, fresh_value) | |
return fresh_value | |
# cache_attempt3.py | |
class MyDjangoCache: | |
def set(self, key, val): | |
# use Django somehow and depend on it | |
pass | |
def get(self, key): | |
return cache.get(key) | |
class MyRedisCache: | |
def set(self, key, val): | |
# use Redis somehow and depend on it | |
pass | |
def get(self, key): | |
return redis.get(key) | |
# views.py | |
my_client = MyClient(url, cache=MyRedisCache(redis_server_ip_address)) | |
# testing_v3.py | |
mock_cache = Mock() | |
my_client = MyClient(url, cache=mock_cache) | |
my_client.get_configs(uuid) | |
assert mock_cache.get.called |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment