Skip to content

Instantly share code, notes, and snippets.

@thebopshoobop
Last active February 19, 2018 10:18
Show Gist options
  • Save thebopshoobop/8f1afe78916fd6b9d63aa2b1bcb262e8 to your computer and use it in GitHub Desktop.
Save thebopshoobop/8f1afe78916fd6b9d63aa2b1bcb262e8 to your computer and use it in GitHub Desktop.
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