Last active
February 19, 2018 10:18
-
-
Save thebopshoobop/8f1afe78916fd6b9d63aa2b1bcb262e8 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
from collections import defaultdict | |
import json | |
from flask import url_for | |
class CachedUrlFor(): | |
def __init__(self): | |
self._cache = defaultdict(dict) | |
def get(self, endpoint, **values): | |
details = tuple(sorted(values.items())) | |
url = self._cache.get(endpoint, {}).get(details) | |
if not url: | |
url = url_for(endpoint, **values) | |
self._cache[endpoint][details] = url | |
return url | |
def clear_cache(self): | |
self._cache = defaultdict(dict) | |
def store_cache(self, file_name): | |
with open(file_name, mode="w") as f: | |
f.write(json.dumps(self._cache)) | |
def load_cache(self, file_name): | |
with open(file_name) as f: | |
self._cache = defaultdict(dict, {**self._cache, **json.loads(f)}) | |
cached_url = CachedUrlFor() | |
cached_url.get('profile', username='John Doe') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment